blob: 04c22356f8b5e8f62122d63d20e8a86a79a8ef17 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
;;; guile-2d
;;; Copyright (C) 2013 David Thompson <dthompson2@worcester.edu>
;;;
;;; Guile-2d is free software: you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; Guile-2d is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Cooperative multi-tasking.
;;
;;; Code:
(define-module (2d coroutine)
#:export (coroutine
colambda
codefine
codefine*
wait)
#:replace (yield)
#:use-module (2d agenda))
(define (coroutine thunk)
"Calls a procedure that can yield a continuation."
(define (handler cont callback . args)
(define (resume . args)
;; Call continuation that resumes the procedure.
(call-with-prompt 'coroutine-prompt
(lambda () (apply cont args))
handler))
(when (procedure? callback)
(apply callback resume args)))
;; Call procedure.
(call-with-prompt 'coroutine-prompt thunk handler))
;; emacs: (put 'colambda 'scheme-indent-function 0)
(define-syntax-rule (colambda args body ...)
"Syntacic sugar for a lambda that is run as a coroutine."
(lambda args
(coroutine
(lambda () body ...))))
;; emacs: (put 'codefine 'scheme-indent-function 1)
(define-syntax-rule (codefine (name ...) . body)
"Syntactic sugar for defining a procedure that is run as a
coroutine."
(define (name ...)
;; Create an inner procedure with the same signature so that a
;; recursive procedure call does not create a new prompt.
(define (name ...) . body)
(coroutine
(lambda () (name ...)))))
;; emacs: (put 'codefine* 'scheme-indent-function 1)
(define-syntax-rule (codefine* (name ...) . body)
"Syntactic sugar for defining a procedure with optional and
keyword arguments that is run as a coroutine."
(define* (name ...)
;; Create an inner procedure with the same signature so that a
;; recursive procedure call does not create a new prompt.
(define* (name ...) . body)
(coroutine
(lambda () (name ...)))))
(define (yield callback)
"Yield continuation to a callback procedure."
(abort-to-prompt 'coroutine-prompt callback))
(define* (wait #:optional (delay 1))
"Yield coroutine and schdule the continuation to be run after delay
ticks."
(yield (lambda (resume) (agenda-schedule resume delay))))
|