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.
(define (test x)
(if (> x 1)
(do-something))
(if (= x 4)
(do-something))
(if (> x 10)
#f))
(test 11)
=> #f
In fact, after reordering the conditions we can remove the last one, but beware: an unspecified value will be returned if x
is not 4
, according to Guile's documentation - in other words, you should always return a value in each case, and an if
expression should have both consequent and alternative parts.
(define (test x)
(if (> x 1)
(do-something))
(if (= x 4)
(do-something)))
(test 11)
=> unspecified
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 than 1
is passed, but if it is less than or equal to 1
the returned value in Python will be None
and in Scheme is unspecified. Also the original function isn't explicitly returning a value - in Python this means that None
will be returned, in Scheme the returned value will be either (do-something)
if x
happens to be 4
, or unspecified in any other case.
do something
does something that result in a side effect? Perhaps if you said what the function was suppose to do we could make a more idiomatic Scheme version for you to look at. The answers so far try to mimic you code and is pretty bad Scheme. – Precatorydo something
has a side effect (which of course it has), so I addressed both issues and added an answer as the only simple and correct answer was in Adam Rosenfield’s comment. – Canescent