(module loops mzscheme ;; This tries to capture the difference between loops done in ;; a traditional way using mutation vs loops through recursion. ;; ;; People seem really confused about this for some reason, and blame ;; a language for not implementing lexical scope when the unexpected ;; happens with: ;; ;; def make_adders(n): ;; results = [] ;; for i in range(n): ;; results.append(lambda x: i + x) ;; return results (require (only (lib "etc.ss") local)) (define-syntax map-range-1 (syntax-rules () ((_ (var n) body ...) (local ((define var 0) (define (iterate) (cond [(< var n) (let ([val (begin body ...)]) (set! var (add1 var)) (cons val (iterate)))] [else '()]))) (iterate))))) (define-syntax map-range-2 (syntax-rules () ((_ (var n) body ...) (local ((define (iterate var) (cond [(< var n) (let ([val (begin body ...)]) (cons val (iterate (add1 var))))] [else '()]))) (iterate 0))))) (define (call-thunk thunk) (thunk)) (for-each call-thunk (map-range-1 (i 5) (lambda () (display i)))) (newline) (for-each call-thunk (map-range-2 (i 5) (lambda () (display i)))) (newline))