问题描述
我正在尝试将一些 Python 代码转换为方案.
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)
我没有在方案中找到回报".当 x > 10 时,我想退出测试功能.如何模拟方案中的回报"?(我正在使用诡计)谢谢
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
推荐答案
在 Scheme 中没有明确的 return
关键字 - 它比这简单得多,最后一个表达式的值表达式序列是返回的表达式.例如,您的 Python 代码将转换为这样,并注意 (> x 10)
案例必须移动到底部,因此如果为真,它可以立即退出函数 (> x 10)
代码>#f 值.
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
事实上,在对条件重新排序后,我们可以删除最后一个,但要注意:如果 x
不是 4
,根据 Guile 的 文档 - 换句话说,您应该始终在每个case 和 if
表达式应该同时包含后续部分和替代部分.
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
顺便说一句,我认为 Python 代码中的逻辑有点偏离.每当传递大于 1
的 x
值时,将始终评估第一个条件,但如果它小于或等于 1
Python 中的返回值将是 None
并且在 Scheme 中是未指定的.此外,原始函数没有明确返回值 - 在 Python 中这意味着 None
将被返回,在 Scheme 中,返回值将是 (do-something)
如果x
恰好是 4
,或者在任何其他情况下未指定.
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.
这篇关于什么是“回报"?在计划?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!