Hrvoje Niksic <hniksic(a)srce.hr> writes:
Can you give two or three simple examples of call/cc usage?
[Michael complies, but with rather hairly examples]
Hrvoje Niksic <hniksic(a)srce.hr> writes:
Uh, I am ashamed to admit that I don't understand these examples.
I
don't know what coroutines are, either.
No shame in that.
Coroutines, btw, are similar in nature to threads, but not as
powerful. Think of being able to have multiple procedures pass
control back and forth to each other, each one remembering its context
when control is passed back to it. Implementing such a beast without
access to continuations would be rather difficult if not impossible,
while it is fairly easy with call/cc.
Could you please mail a trivial example, or a URL pointer to such?
Here are a couple of straightforward examples, both taken from Kent
Dybvig's excellent book _The Scheme Programming Language_.¹
(define product
(lambda (ls)
(call/cc
(lambda (break)
(let f ((ls ls))
(cond
((null? ls) 1)
((= (car ls) 0) (break 0))
(else (* (car ls) (f (cdr ls))))))))))
(define member
(lambda (x ls)
(call/cc
(lambda (break)
(do ((ls ls (cdr ls)))
((null? ls) #f)
(if (equal? x (car ls))
(break ls)))))))
Both of these show the most common use of call/cc (in my personal
experience), which is to allow a nonlocal exit from a recursive call.
Other uses are certainly widespread, but this is the easiest one to
understand for people unaccustomed to thinking about continuations.
I hope that these examples are clearer. If they or the benefit of
ready access to continuations is still not clear, I will think of
something else.
¹This book is a good reference as well as an excellent book with which
to learn Scheme. It is probably one of the main reasons why I was
able to start programming Scheme very easily, having used CL and
elisp before ever seeing Scheme.
-Justin