scheme - 如何在方案编程中使用 if 语句?
问题描述
我刚开始学习方案语言,下面是一个我有点卡住的问题(我的代码有什么问题吗,因为错误消息有点奇怪)
Prompt: Define a procedure over-or-under which takes in a number x and a number y and returns the following:
-1 if x is less than y
0 if x is equal to y
1 if x is greater than y
What I've tried so far is :
(define (over-or-under x y)
(if (< x y)
-1)
(if (= x y)
0)
(if (> x y)
1)
)
The error message is :
scm> (load-all ".")
Traceback (most recent call last):
0 (adder 8)
Error: str is not callable: your-code-here
scm> (over-or-under 5 5)
# Error: expected
# 0
# but got
解决方案
的语法if
是:
(if condition expression1 expression2)
条件为真时为表达式1的值,否则为表达式2的值。
在您的函数中,您使用:
(if condition expression1)
这是不允许的。注意,另外三个if
s一个接一个是顺序执行的,实际只使用最后一个的值,作为函数调用的返回值。
解决此问题的一种方法是使用 的“级联” if
:
(define (over-or-under x y)
(if (< x y)
-1
(if (= x y)
0
1)))
请注意,正确的对齐方式可以明确不同表达式的执行顺序。如果(< x y)
为真,则值 -1 是 的结果if
,但是,由于它是函数的最后一个表达式,因此它也是函数调用的值。如果不是这样,我们执行“inner” if
,检查 x 是否等于 y,等等。还要注意,在第三种情况下,不需要检查 x 是否大于 y,因为它肯定是正确的,因为 x 不小于 y,也不等于 y。
最后,请注意 x 的“级联”是如此普遍,以至于在 scheme 中存在一种在语法上更方便的方式来用特定的cond
表达式来表达它:
(cond (condition1 expression1)
(condition2 expression2)
...
(else expressionN))
所以你可以这样重写函数:
(define (over-or-under x y)
(cond ((< x y) -1)
((= x y) 0)
(else 1)))
推荐阅读
- java - Execute a .jar file using shell script
- c# - 不在管理员模式下时,在 TLS 1.2 连接期间无法创建 SSL/TLS 安全通道错误
- reactjs - How to use React Router's Link with a variable pathname?
- python - how to resolve this error InvalidArgumentError: sequential_6_input:0 is both fed and fetched
- php - How to update multiple MySQL table entries with different id?
- jquery - 如何拆分方括号内的字符串并使用JQUERY放入数组中
- javascript - 以编程方式修改url 以添加 "?example-text=50" 和前缀 "
" - javascript - 如何使用整数作为 JSON 对象键
- java - 运行 Spring Boot JPA 测试时,数据库中没有保留任何值
- python - 如何在 Jenkins 的无 GUI 模式下在锁定的远程机器上成功运行 AutoIT 脚本?