Могу ли я иметь подпрограмму из трех функций, используя продолжения в Схеме? - PullRequest
1 голос
/ 01 декабря 2009

Можно ли добавить сюда другую функцию 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 ]

4 голосов
/ 01 декабря 2009

Из "Языка программирования схемы"

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!
0 голосов
/ 13 июня 2011

Как то так?

(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)
...