使用两个以上的协同程序

时间:2016-03-30 20:05:07

标签: scheme coroutine continuations

所以我有以下“cor.scm”

(define (range-gen str stp inc)
  (call/cc
   (lambda (yield)
     (yield (lambda ()
              (let ([i str])
            (cond ([< str stp]
                   (set! str (+ i inc))
                   i)
                  (else #f))))))))

(define continue? (range-gen 0 10 1))

(define it (range-gen 0 10 1))

(define (routine-a cc)
  (let loop ()
    (cond ((continue?)
       (printf "Blah ~A~N" (it))
       (set! cc (call/cc cc))
       (loop)))))

(define (routine-b cc)
  (let loop ()
    (cond ((continue?)
       (printf "Blar ~A~N" (it))
       (set! cc (call/cc cc))
       (loop)))))

例程-a和b是协程。我希望有第三个(第n个)例程,它将进入循环或其他一些控制方案,即a-> b-> c ... - > c直到满足结束条件,或者甚至是 - &GT; B-&GT; A-&GT; c..a-&以及c

编辑: 调用(routine-a routine-b)的输出是:

; loading cor.scm ...

1> (routine-a routine-b) ;Starts coroutines, notice how they use the continue?
Blah 0                   ;generator to share state, only going through the cycle
Blar 1                   ;5 times each out of the total 10 continue? calls that
Blah 2                   ;will return true.
Blar 3
Blah 4
Blar 5
Blah 6
Blar 7
Blah 8
Blar 9
2> (routine-a routine-b) ;returns nothing, the continue generator now will only return #f
3>                       ;which is the expected behaivor :)

另外,在两个协同程序之间传递数据的最佳方式是什么?现在我会在两个函数的范围内使用一个变量,并允许它们改变它的状态(这就是我正在用continue生成器来跟踪这是什么循环)但是我想通过如果可能的话。

0 个答案:

没有答案