循环中如何工作?
问题描述:
我在理解循环如何在方案中工作时遇到一些困难。特别是这段代码运行,但我不知道为什么循环中如何工作?
(define (bubblesort alist)
;; this is straightforward
(define (swap-pass alist)
(if (eq? (length alist) 1)
alist
(let ((fst (car alist)) (scnd (cadr alist)) (rest (cddr alist)))
(if (> fst scnd)
(cons scnd (swap-pass (cons fst rest)))
(cons fst (swap-pass (cons scnd rest)))))))
; this is mysterious--what does the 'for' in the next line do?
(let for ((times (length alist))
(val alist))
(if (> times 1)
(for (- times 1) (swap-pass val))
(swap-pass val))))
我想不出什么(let for ((
应该在这里做的,而在倒数第二行的for
表情也有点过把 - 我有翻译抱怨for
只采取一个单一的论点,但这里似乎需要两个。
想到这里发生了什么?
答
这不是一个for循环,这是一个名为let
。它所做的是创建一个名为for
的函数,然后调用它; “循环”行为是由函数中的递归引起的。调用函数loop
更符合惯用,顺便说一句。例如。
(let loop ((times 10))
(if (= times 0)
(display "stopped")
(begin (display "still looping...")
(loop (- times 1)))))
被这实际上不是使用for
语言功能,但只是使用let
的变化,让您轻松地编写递归函数扩展到像
(letrec ((loop (lambda (times)
(if (= times 0)
(display "stopped")
(begin (display "still looping...")
(loop (- times 1)))))))
(loop 10))
非常感谢,我按照你所描述的扩展了命名的let,现在对我更有意义。 – 2012-02-16 15:11:20