This is the mail archive of the guile@sourceware.cygnus.com mailing list for the Guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: question about r5rs (was Re: pack/unpack)


sen_ml@eccosys.com writes:

> ah, thank you for that explanation!  knowing the definition of a thunk
> is very helpful.  is there a good glossary of terms around somewhere?

Not that I know of. 

> i would also like to learn what a continuation is.  not having had
> much college-level (or above) c.s. training, some of these terms are
> lost on me.

Okay, here I go shooting off my mouth: a continuation is the remainder of a
computation. Imagine your program going through all kinds of steps while it
is being executed. At any certain step it does, there are steps it has done
already and others that are still to do; those are the continuation.

For example, look at the procedure
(define (factorial n)
  (if (= n 0)
      1
      (* (factorial (- n 1))   n)))
                             ^ cut here

If you look at the marked place in that procedure, the first thing the
continuation of the recursive call to factorial does is multiply the result
of the call by n, it then returns from the current invocation etc.

The nice thing about continuations in Scheme is that they are first class,
i.e. you can access them via call-with-current-continuation (sometimes
called call/cc 'cause the-other-name-is-quite-a-mouthful). See R5RS for a
formal description of call/cc. You can think of it as a better version of
the C setjmp/longjmp calls.

You can, for example, use call/cc to implement an error throwing/catching
facility or a nonlocal return. Here's a nonlocal return example:

(define (return-example return)
  (define (f i)
    (let ((x (random 5)))
      (cond
       ((= x 0) (return 'aborted))
       ((> i 2) #f)
       (else 
	(display i) (display " ")
	(f (+ i 1))
	(display i) (display " ")))))
  (newline)
  (f 0))

To try it execute (call-with-current-continuation proc) in a repl several
times. As you'll notice, a call to RETURN in F aborts the whole stack of
recursive calls to F, not only the current one. It's as if you jump right
behind the closing parenthesis of the call/cc call.

I hope I made something clear,
David

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]