I am trying to translate some python code to scheme.
def test(x):
if x > 1:
do something
if x > 10:
return
if x == 4:
do something
test(11)
I did not find the "return" in scheme. I want to quit from the test function when x >10. How can I simulate the "return" in scheme? (I am using guile) Thanks
In Scheme there isn't an explicit
return
keyword - it's a lot simpler than that, the value of the last expression in a sequence of expressions is the one that gets returned. For example, your Python code will translate to this, and notice that the(> x 10)
case had to be moved to the bottom, so if it's true it can exit the function immediately with a#f
value.In fact, after reordering the conditions we can remove the last one, but beware: an unspecified value will be returned if
x
is not4
, according to Guile's documentation - in other words, you should always return a value in each case, and anif
expression should have both consequent and alternative parts.And by the way, I believe the logic in the Python code is a bit off. The first condition will always be evaluated whenever a value of
x
greater than1
is passed, but if it is less than or equal to1
the returned value in Python will beNone
and in Scheme is unspecified. Also the original function isn't explicitly returning a value - in Python this means thatNone
will be returned, in Scheme the returned value will be either(do-something)
ifx
happens to be4
, or unspecified in any other case.You may use
call/cc
You can return no value using
(k)
.Read about Continuations.
As others have said, the last expression's value in a function is its return value, so you just have to arrange for exclusive execution pathways in your code, to achieve this effect.
(if <test> <consequent> <alternative>)
is the basic branching operation in Scheme:Or we could use
cond
to avoid the needlessly nested structure in the code:In Racket the most literal translation is:
The
let/ec
is short for let/escape-continuation. Look up the equivalent control structure in the manual for your Scheme implementation of choice.The example displays one ! and then returns 42.
The implicit
return
of Scheme can be illustrated by comparing how you can implement a simple function, such assquare
, in Python and scheme.In Python:
In Scheme: