[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Continuation examples (was Re: So, what the heck is a continuation anyway?)



Eric Kidd wrote:
>Kent Pitman once showed me a profoundly evil bit of Scheme code.  Here's
>a recreation I keep sitting in home directory:
>
>((call-with-current-continuation
>  (lambda (goto)
>    (letrec ((start
>	      (lambda ()
>		(display "start")
>		(newline)
>		(goto next)))
>	     (froz
>	      (lambda ()
>		(display "froz")
>		(newline)
>		(goto last)))
>	     (next
>	      (lambda ()
>		(display "next")
>		(newline)
>		(goto froz)))
>	     (last
>	      (lambda ()
>		(display "last")
>		(newline)
>		#f)))
>      start))))
>
>This fragment implements an honest-to-goodness GOTO in Scheme.  It uses
>all the major Scheme features--continuations, lexical scoping, closures,
>tail-calls and first class functions--all at once.  It's beautiful.  And
>it's even more evil than my generator-in-C hack. :-)  Once you
>understand it, you've got a good handle on most of Scheme's most
>counter-intuitive features.
>
>Yes, I'm going to leave deciphering this code as an exercise for the
>reader.  (Hint: The continuation returns into a '(' ')' pair, so it
>calls the argument passed to 'goto'.)

The code is actually pretty easy to understand if you use the
appropriate tool.  Here are two screen dumps showing what DrScheme's
data flow analysis tool (MrFlow) computes for that particular piece of
code.

The first screen dump shows that the call/cc expression returns four
functions: three functions that take no arguments and never return
anything ("_" is nothing), and one function that takes no arguments
and returns #f (case-lambda is the same thing as lambda, for our
purpose here).

http://www.ccs.neu.edu/home/meunier/DrScheme-MrFlow-1.gif

The second screen dump shows where these four functions are coming
from.

http://www.ccs.neu.edu/home/meunier/DrScheme-MrFlow-2.gif

Philippe