logoalt Hacker News

Emulating Goto in Scheme with Continuations

39 pointsby usuallylast Thursday at 5:58 PM13 commentsview on HN

Comments

Trung0246today at 8:23 PM

Here's my very funny implementation of delimited continuation in plain C with zero ASM usage (with help from a specific compiler built-in)

https://gist.github.com/Trung0246/8f801058212d3bbbef82690a31...

Demo (old version with outdated compile flag but still works): https://godbolt.org/z/n9ch4TM3s

It works for gcc/clang/msvc with -O0, -O1, -O2, and even -O3

taerictoday at 4:33 PM

I confess I like Common Lisp's TAGBODY far more than I feel like I should. Having constrained GOTO semantics to a short section of the codebase is surprisingly useful.

show 5 replies
soegaardtoday at 7:23 PM

If you are into continuations, check Friedman's papers on ReadScheme.

https://github.com/schemedoc/bibliography/blob/master/page6....

In particular look at "Programming with Continuations", "Engines Build Process Abstractions" and "Continuations and Coroutines".

umanwizardtoday at 6:25 PM

Note that the example program:

  (define (displayln obj)
    (display obj)
    (newline))
  
  (define cont #f)
  
  (displayln
    (call/cc 
      (lambda (k)
        (set! cont k)
        "cont set")))
  
  (begin
    (displayln "procedure called")
    (displayln "after procedure call")
    (cont "continuation called")
    (displayln "after continuation call"))
will only terminate if pasted into a REPL, not if invoked from a file.

This is because every top-level form in the REPL has an implicit continuation "return to the REPL and read more input".

So after "continuation called" is printed, we go back to the prompt and await more input.

However, if this code is saved in a file and you run it (e.g. "guile my-script.scm") then the continuation of the top-level `displayln` call is the top-level `begin` form, and we enter an infinite loop.