2010/05/24

call/cc sum1-n, reverse

(call/cc identity) が、なるほど!だったので。
;; http://www.rakunet.org/TSNET/topics/compare.html#scheme
(define (sum1-n n)
(let ((total 0)
(i 0))
(let1 next (call/cc identity)
(if (< n i)
total
(begin
(set! total (+ total i))
(set! i (+ i 1))
(next next))))))
(sum1-n 10)
(define (sum1-n n)
(let ((total 0)
(i 0))
(let/cc break
(let1 next (call/cc identity)
(if (< n i)
(break total)
(begin
(set! total (+ total i))
(set! i (+ i 1))
(next next)))))))
(sum1-n 10)
; -> 55

;; reverse
(define (my-reverse ls)
(let ((ls ls)
(acc '()))
(let/cc return
(let1 next (call/cc identity)
(if (null? ls)
(return acc)
(begin
(set! acc (cons (car ls) acc))
(set! ls (cdr ls))
(next next)))))))
(my-reverse '(1 2 3 4 5))


プログラミングGauche

0 件のコメント:

コメントを投稿