PasteRack.org
Paste # 38752
2023-02-27 21:49:45

Fork as a new paste.

Paste viewed 650 times.


Embed:

Coroutines

  1. #lang racket
  2. ;; coroutines implementation from https://hillside.net/plop/plop2001/accepted_submissions/PLoP2001/dferguson0/PLoP2001_dferguson0_1.pdf
  3. (define (coroutine-maker proc)
  4.   (define saved-continuation '())
  5.   (define (update-continuation! v)
  6.     (displayln "updating")
  7.     (set! saved-continuation v))
  8.   (define resumer (resume-maker update-continuation!))
  9.   (define first-time #t)
  10.   (define (f value)
  11.     (cond
  12.       [first-time
  13.        (set! first-time #f)
  14.        (proc resumer value)]
  15.       [else (saved-continuation value)]))
  16.   f)
  17.  
  18. (define ((resume-maker update-proc!) next-coroutine value)
  19.   (define (receiver continuation)
  20.     (update-proc! continuation)
  21.     (next-coroutine value))
  22.   (call-with-current-continuation receiver))
  23.  
  24. ;; tests
  25.  
  26. (define ping
  27.   (coroutine-maker
  28.    (lambda (resume value)
  29.      (displayln "Pinging 1")
  30.      (resume pong value)
  31.      (displayln "Pinging 2")
  32.      (resume pong value)
  33.      (displayln "Pinging 3")
  34.      (resume pong value))))
  35.  
  36. (define pong
  37.   (coroutine-maker
  38.    (lambda (resume value)
  39.      (displayln "Ponging 1")
  40.      (resume ping value)
  41.      (displayln "Ponging 2")
  42.      (resume ping value)
  43.      (displayln "Ponging 3")
  44.      (resume ping value))))
  45.  
  46. (ping 1)

=>

Pinging 1

updating

Ponging 1

updating

Pinging 2

updating

Ponging 2

updating

Pinging 3

updating

Ponging 3

updating

1