4

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?

Aslan986
  • 9,984
  • 11
  • 44
  • 75

1 Answers1

5

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.

leppie
  • 115,091
  • 17
  • 196
  • 297
  • Thank you for your answer, but it is not what I need. I DO NOT want that the clean-up part is executed. – Aslan986 Aug 20 '12 at 12:20
  • @Aslan986: Just skip the dynamic-wind bit then, sorry I misread your question :) Editing answer. – leppie Aug 20 '12 at 12:30
  • @Aslan986: Your example does not really make sense why you would want this. – leppie Aug 20 '12 at 12:35
  • @Ieppie: I would like to do something like this: http://eval.ironscheme.net/?id=67 . (I know I can easly do this with a closure). I need a C-style `return` function. – Aslan986 Aug 20 '12 at 12:48
  • @Aslan986: Unfortunately IronScheme does not have full blown continuations, so I can't really test it or suggest a working example unless I go to some other Scheme. I assume you want something like an infinite generator akin to `yield` in some languages. As you said, doing it with a closure is the normal way, and is the one I would use. – leppie Aug 20 '12 at 13:21