無限リスト
Scheme の call/cc を理解するために。
Python の yield を真似してみる。こんなん。
def natural(): n=0 while 1: yield n n += 1
>>> a=natural()
>>> a.next()
0
>>> a.next()
1
>>> a.next()
2で、Scheme 版。
pos とか restart とかいうよくわからない変数が外に出てるのが明らかによくないけど、どうしたらいいのかわからん…。(define pos '()) (define restart #f) (define (natural) (call/cc (lambda (yield) (let loop ((n 0)) (if restart (begin (set! restart #f) (pos)) (call/cc (lambda (cont) (begin (set! pos cont) (set! restart #t) (yield n))))) (loop (+ n 1))))))gosh> (natural)
0
gosh> (natural)
1
gosh> (natural)
2
gosh> (natural)
3
gosh>