Pse*_*ias 5 scheme for-loop racket
我在理解循环如何在方案中工作时遇到一些困难.特别是这个代码运行但我不知道为什么
(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))))
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚(let for ((应该在这里做什么,而for倒数第二行中的表达式也有点偏离 - 我已经让翻译抱怨for只需要一个参数,但在这里看起来似乎拿两个.
关于这里发生了什么的任何想法?
Fre*_*Foo 14
这不是for循环,这是一个名字let.它的作用是创建一个名为的函数for,然后调用它; "循环"行为是由函数中的递归引起的.调用函数loop更惯用,顺便说一下.例如
(let loop ((times 10))
(if (= times 0)
(display "stopped")
(begin (display "still looping...")
(loop (- times 1)))))
Run Code Online (Sandbox Code Playgroud)
扩展到类似的东西
(letrec ((loop (lambda (times)
(if (= times 0)
(display "stopped")
(begin (display "still looping...")
(loop (- times 1)))))))
(loop 10))
Run Code Online (Sandbox Code Playgroud)