call/cc

2008年04月29日

例1:
(define (f)
  (call/cc (lambda (escape)
             (begin (print 1)   ; beginでくるんでるのはわざと
                    (print 2)
                    (escape 10) ; call/cc の外に大域脱出!
                    (print 3)))))
(print (f))
例2:
(print (+ 3 (call/cc (lambda (c) (+ 3 (c 4)))))) ; 7
続きを読む

(22:38) Φ
例1:
(define cont #f)

(print (+ 5 (call/cc (lambda (c) (begin (set! cont c) 1))))) ;; expects 6

(cont 11) ; 16
(cont 21) ; 26
例2:call/ccの位置を変えて試してみる
(define cont #f)

(print (+ 6 (+ 5 (call/cc (lambda (c) (begin (set! cont c) 1))) 10) 12)) ;; expects 34

(cont 11) ; 44 = 6 + (5 + * + 10) + 12 = 33 + 11 = 44
(cont 21) ; 54 = 6 + (5 + * + 10) + 12 = 33 + 21 = 54
例3:
(define x #f)

(begin
  (print 0)
  (print 1)
  (call/cc (lambda (z) (set! x z)))
  (print 2)
  (print 3))

(x #t)
例4:λで包まれていたりとか
(define cont #f)

(define (a)
  (print 1)
  ((lambda ()
     (print 2)
     (call/cc (lambda (c) (set! cont c)))
     (print 3)))
  (print 4))

(a)

(cont 0)
例5:
(define cont #f)
(define a (lambda ()
            (+ 1
               (+ 2 3)
               (call/cc (lambda (c) (set! cont c) 4))
               (+ 5 6))))

(print (a))      ;; expects 21 = 1 + (2 + 3) + 4 + (5 + 6)
(cont 5)         ;; expects 22 = 1 + (2 + 3) + 5 + (5 + 6)
例6:
(define cont #f)
(define a (lambda ()
  (if (call/cc (lambda (c) (set! cont c) #f))
      (print 1)
      (print 0))
  (print 9)))

(a)
(cont #t)
続きを読む

(22:31) Φ