4
votes

I'm trying to implement a return function in Scheme R6RS. I want something such that:

(lambda ()
  (do-some-job-before)
  (return some-value)
  (do-some-job-after))

executes (do-some-job-before), do not execute (do-some-job-after) and the final value of the lambda function in some-value.

I guess I have to use a continuation. I tried:

(define return #f)
(call/cc (lambda (k)
           (set! return k)))

but it does not work; e.g

(+ 2 (return 3)) ; -> 3 (and not 5 as I expected)

How can i do this?

1

1 Answers

5
votes

Edited: Misread question.

Very easy in fact :)

(call/cc 
  (lambda (return)
    (printf "before\n")
    (return 3)
    (printf "after\n")))

Example here.

Note: You cannot generalize this, except if you wrap it in syntax from an unhygienic macro.