我可以使用Scheme中的continuation来实现三个函数的共同例程吗?

时间:2009-12-01 15:34:38

标签: functional-programming scheme racket continuations

是否可以在此处添加另一个函数procC,以便评估序列为procA-> procB-> procC-> procA ...?

(define (procA another-fun)
  (let loop ((n 5))
    (display "In Proc A \n")
    (set! another-fun (call/cc another-fun))
    (when (> n 0)
      (loop (- n 1)))))

(define (procB another-fun)
  (let loop ((n 5))
    (display "In Proc B  \n")
    (set! another-fun (call/cc another-fun))
    (when (> n 0)
      (loop (- n 1)))))

2 个答案:

答案 0 :(得分:4)

来自“计划编程语言”

http://www.scheme.com/tspl4/further.html#./further:h3

(define lwp-list '()) ; SO's highlighter gets confused
(define lwp
  (lambda (thunk)
    (set! lwp-list (append lwp-list (list thunk)))))

(define start
  (lambda ()
    (let ([p (car lwp-list)])
      (set! lwp-list (cdr lwp-list))
      (p))))

(define pause
  (lambda ()
    (call/cc
      (lambda (k)
        (lwp (lambda () (k #f)))
        (start)))))


(lwp (lambda () (let f () (pause) (display "h") (f))))
(lwp (lambda () (let f () (pause) (display "e") (f))))
(lwp (lambda () (let f () (pause) (display "y") (f))))
(lwp (lambda () (let f () (pause) (display "!") (f))))
(lwp (lambda () (let f () (pause) (newline) (f))))
(start)  hey!
         hey!
         hey!
         hey!

答案 1 :(得分:0)

这样的东西?

(define (puts . lst)
  (map display lst)
  (newline))

(define (A some-fun more-fun)
  (let loop ((n 3))
    (puts "In A with " some-fun " and " more-fun " and n=" n)
    (let-values (((s m) (call/cc (lambda (next-iter) (some-fun more-fun next-iter)))))
      (set! some-fun s)
      (set! more-fun m))
    (when (> n 0) (loop (- n 1)))))
(define (B some-fun more-fun)
  (let loop ((n 3))
    (puts "In B with " some-fun " and " more-fun " and n=" n)
    (let-values (((s m) (call/cc (lambda (next-iter) (some-fun more-fun next-iter)))))
      (set! some-fun s)
      (set! more-fun m))
    (when (> n 0) (loop (- n 1)))))
(define (C some-fun more-fun)
  (let loop ((n 3))
    (puts "In C with " some-fun " and " more-fun " and n=" n)
    (let-values (((s m) (call/cc (lambda (next-iter) (some-fun more-fun next-iter)))))
      (set! some-fun s)
      (set! more-fun m))
    (when (> n 0) (loop (- n 1)))))

(A B C)