Implement a return function - scheme

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?

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.

Related

Hygienic macro r7rs : Return second expression value

I'm currently learning some r7rs and I am trying to implement a macro 'begin' as following :
(begin0 expr0 expr1 ... expr2)
With expr being a regular expression (Like (set! x (+ x 1)))
And begin0 as a macro that evaluates all the expression but return only the expr1 result.
For example :
(let ((year 2017))
(begin1 (set! year (+ year 1))
year
(set! year (+ year 1))
year))
It musts return 2018
I've created a begin function first :
(define-syntax begin0
(syntax-rules ()
((begin-0 body-expr-0 body-expr-1 ...)
(let ((tmp body-expr-0)) body-expr-1 ... tmp))))
And now, I'm trying to understand how I can do to return the value of "body-expr-1" ?
I've done the following code, but it says that I'm missing some ellipsis and I don't understand how to do it.
(define-syntax begin1
(syntax-rules ()
((begin1 body-expr-0 body-expr-1 ... body-expr-2)
(let ((tmp body-expr-0) body-expr-1 ... tmp)
(cond (eq? tmp body-expr-1)
(begin . tmp))))))
I hope that it is understandable enough, thanks for the answers.
This can be done, but the macro will interfere such that you cannot do all the things with begin1 as with begin.
(define-syntax begin1
(syntax-rules ()
((_ expr0 expr1 exprn ...)
(begin
expr0
(let ((result expr1))
exprn ...
result)))))
The code that does not work is this:
(begin1
(define global1 10)
test3
(define global2 20))
The reason is obvious. It expands to:
(begin1
(define global1 10)
(let ((result~1 test3))
(define global2 20)
result~1))
The second define will be changed to a letrec such that the variable global2 is only available for the duration of the let. I have no fix for this since it requires you to be able to do global define from a closure.
begin1 is rather strange feature. In Racket and perhaps other Scheme dialects we have begin0 that returns the result of the first expression. This is very useful. eg. here is a counter:
(define (get-counter from)
(lambda ()
(let ((tmp from))
(set! from (+ from 1))
tmp)))
And with begin0:
(define (get-counter from)
(lambda ()
(begin0
from
(set! from (+ from 1)))))
In Racket begin0 is a primitive. So it is a form supported in the fully expanded program and thus implemented in C, just like begin..
So, I found a possible way to do it, I didn't though we could just ask a condition on the immediate value :
(define-syntax begin1
(syntax-rules ()
((begin1 body-expr-0 body-expr-1 body-expr-2 ...)
(if body-expr-1
(write body-expr-1)))))

Control flow in a Scheme program having call-with-current-continuation

I am new to Scheme programming and have been trying to understand the control flow of the programs having call-with-current-continuation in them. To be more specific, I want to know when the call to any continuation is invoked where is the control transferred and what happens after that. It would be really helpful if the below mentioned program is considered for the explanation.
(define call/cc call-with-current-continuation)
(define amb-exit '())
(define amb
(lambda ()
(call/cc
(lambda (m)
(call/cc
(lambda (f1)
(set! amb-exit (lambda () (f1 'exit)))
(m 1)))
(call/cc
(lambda (f2)
(set! amb-exit (lambda () (f2 'exit)))
(m 2)))
(call/cc
(lambda (f3)
(set! amb-exit (lambda () (f3 'exit)))
(m 3)))))))
(define back (lambda () (amb-exit)))
Now, I try to run the code this way (define a (amb)) and then I get the value in the terminal like this ;Value: a. Then in the terminal I check the value of a which returns me ;Value: 1. Then I call (back) I get a with the new value ;Value: 2. So on...
I know that when I do (define a (amb) the continuation f1 is invoked in the statement (set! amb-exit (lambda () (f1 'exit))) which transfers the control back to the first inner call/cc and the f1 continuation returns exit.
The thing that I am not able to understand is why the ;Value: a is ;Value: 1 instead of the value exit which is returned by f1?
The moment this part (f1 'exit) is executed, control returns back to first inner call/cc abandoning whatever (in this case (m 1)) after it.
So, this part (m 1) should never be invoked because the first inner continuation i.e. f1 is returned with exit even before hitting (m 1).
Any helpful comments regarding call-with-current-continuation in Scheme would also be appreciated.
Note: Using MIT/GNU Scheme
No, when you do (define a (amb)) the continuation f1 is not invoked, because it is behind (i.e. inside) a lambda.
No, (set! amb-exit (lambda () (f1 'exit))) sets amb-exit to the lambda function, and then the control passes to (m 1) which does invoke the continuation m. Which returns 1 from (amb) in (define a (amb)), which thus sets a to 1.
When you later call (back) it calls (amb-exit) which at that point invokes the f1 continuation with (f1 'exit) which returns the value 'exit from the (call/cc (lambda (f1) ...)) form. This value is discarded, and control passes into the (call/cc (lambda (f2) ...)) form, with similar effects.

Does call/cc in Scheme the same thing with yield in Python and JavaScript?

Does call/cc in Scheme the same thing with yield in Python and JavaScript?
I am not clear about generators. In my opinion, yield gives a language the ability to generate iterators without pain. But I am not sure whether I am right.
Does call/cc in Scheme has something related to yield in other languages? If so, are they the same thing, or what is the difference?
Thanks!
call/cc is a much more general language feature than generators. Thus you can make generators with call/cc, but you cannot make call/cc with generators.
If you have a program that computes values and use those values in other places its basically a step machine.. One might think of it as a program that have one function for each step and a continuation for the rest of the steps. Thus:
(+ (* 3 4) (* 5 6))
Can be interpreted as:
((lambda (k)
(k* 3 4 (lambda (v34)
(k* 5 6 (lambda (v56)
(k+ v34 v56 k)))))
halt)
The k-prefix just indicate that it's a CPS-version of the primitives. Thus they call the last argument as a function with the result. Notice also that the order of evaluation, which is not defined in Scheme, is in fact chosen in this rewrite. In this beautiful language call/cc is just this:
(define (kcall/cc kfn k)
(kfn (lambda (value ignored-continuation)
(k value))
k))
So when you do:
(+ (* 3 4) (call/cc (lambda (exit) (* 5 (exit 6)))))
; ==> 18
Under the hood this happens:
((lambda (k)
(k* 3 4 (lambda (v34)
(kcall/cc (lambda (exit k)
(exit 6 (lambda (v6)
(k* 5 v6 k)))
k))))
halt)
By using the substitution we can prove that this actually does exactly as intended. Since the exit function is invoked the original continuation is never called and thus the computation cancelled. In contrast to call/cc giving us this continuation that doesn't seem obvious it's no magic in CPS. Thus much of the magic of call/cc is in the compiler stage.
(define (make-generator procedure)
(define last-return values)
(define last-value #f)
(define (last-continuation _)
(let ((result (procedure yield)))
(last-return result)))
(define (yield value)
(call/cc (lambda (continuation)
(set! last-continuation continuation)
(set! last-value value)
(last-return value))))
(lambda args
(call/cc (lambda (return)
(set! last-return return)
(if (null? args)
(last-continuation last-value)
(apply last-continuation args))))))
(define test
(make-generator
(lambda (collect)
(collect 1)
(collect 5)
(collect 10)
#f)))
(test) ; ==> 1
(test) ; ==> 5
(test) ; ==> 10
(test) ; ==> #f (procedure finished)
One might make a macro to make the syntax more similar, but it's just sugar on top of this.
For more examples I love Matt Mights page with lots of examples on how to use continuations.
Here's code to define a generator:
(define-syntax define-generator
(lambda (x)
(syntax-case x (lambda)
((stx name (lambda formals e0 e1 ...))
(with-syntax ((yield (datum->syntax (syntax stx) 'yield)))
(syntax (define name
(lambda formals
(let ((resume #f) (return #f))
(define yield
(lambda args
(call-with-current-continuation
(lambda (cont)
(set! resume cont)
(apply return args)))))
(lambda ()
(call-with-current-continuation
(lambda (cont)
(set! return cont)
(cond (resume (resume))
(else (let () e0 e1 ...)
(error 'name "unexpected return"))))))))))))
((stx (name . formals) e0 e1 ...)
(syntax (stx name (lambda formals e0 e1 ...)))))))
There are examples of the use of generators at my blog. Generators use call-with-current-continuation, in a manner similar to yield in Python, but are much more general.
You can implement generators with call/cc. Here is an example:
coroutines.ss
They work in a similar way to python and ECMAScript generators.

Is there anyway to check if a function return nothing in Scheme?

Is there anyway to check if a function return nothing in Scheme?
For example:
(define (f1)
(if #f #f)
)
or
(define (f2) (values) )
or
(define (f3) (define var 10))
How can I check if f return nothing?
Thanks in advance.
Yes. You can wrap the call in something that makes a list of the values. eg.
(define-syntax values->list
(syntax-rules ()
((_ expression)
(call-with-values (lambda () expression)
(lambda g (apply list g))))))
(apply + 5 4 (values->list (values))) ; ==> 9
(null? (values->list (values))) ; ==> #t
Your procedure f2 does return exactly one value and it's undefined in the report (Scheme standard). That means it can change from call to call and the result of (eq? (display "test1") (display "test2")) is unknown.
Implementations usually choose a singleton value to represent the undefined value, but you can not depend on it. Implementations are free to do anything. eg. I know that in at least one Scheme implementations this happens:
(define test 10)
(+ (display 5) (set! test 15))
; ==> 20 (side effects prints 5, and test bound to 15)
It would be crazy to actually use this, but it's probably useful in the REPL.
In GNU Guile the function for checking this is unspecified?:
(unspecified? (if #f #f)); returns #t
(unspecified? '()); returns #f

lambda functions and memory in scheme

I don't understand why if I write
(define (iter-list lst)
(let ((cur lst))
(lambda ()
(if (null? cur)
'<<end>>
(let ((v (car cur)))
(set! cur (cdr cur))
v)))))
(define il2 (iter-list '(1 2)))
and call (il2) 2 times I have printed: 1 then 2
(that's the result I want to have)
But if I don't put (lambda () and apply (il2) 2times I obtain then 1
In other words why associating the if part to a function lambda() makes it keep the memory of what we did when we applied the function before?
This is what's happening. First, it's important that you understand that when you write this:
(define (iter-list lst)
(let ((cur lst))
(lambda ()
...)))
It gets transformed to this equivalent form:
(define iter-list
(lambda (lst)
(let ((cur lst))
(lambda ()
...))))
So you see, another lambda was there in the first place. Now, the outermost lambda will define a local variable, cur which will "remember" the value of the list and then will return the innermost lambda as a result, and the innermost lambda "captures", "encloses" the cur variable defined above inside a closure. In other words: iter-list is a function that returns a function as a result, but before doing so it will "remember" the cur value. That's why you call it like this:
(define il2 (iter-list '(1 2))) ; iter-list returns a function
(il2) ; here we're calling the returned function
Compare it with what happens here:
(define (iter-list lst)
(let ((cur lst))
...))
The above is equivalent to this:
(define iter-list
(lambda (lst)
(let ((cur lst))
...)))
In the above, iter-list is just a function, that will return a value when called (not another function, like before!), this function doesn't "remember" anything and returns at once after being called. To summarize: the first example creates a closure and remembers values because it's returning a function, whereas the second example just returns a number, and gets called like this:
(define il2 (iter-list '(1 2))) ; iter-list returns a number
(il2) ; this won't work: il2 is just a number!
il2 ; this works, and returns 1
When you wrap the if in a lambda (and return it like that), the cur let (which is in scope for the if) is attached to the lambda. This is called a closure.
Now, if you read a little bit about closures, you'll see that they can be used to hold onto state (just like you do here). This can be very useful for creating ever incrementing counters, or object systems (a closure can be used as a kind of inside out object).
Note that in your original code, you renamed lst as cur. You didn't actually need to do that. The inner lambda (the closure to be) could have directly captured the lst argument. Thus, this would produce the same result:
(define (iter-list lst)
(lambda ()
...)) ; your code, replace 'cur' with 'lst'
Here are some example of other closure-producing functions that capture a variable:
(define (always n)
(lambda () n))
(define (n-adder n)
(lambda (m) (+ n m)))
(define (count-from n)
(lambda ()
(let ((result n))
(set! n (+ n 1))
result)))

Resources