首页 > 解决方案 > 如何在方案编程中使用 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

标签: scheme

解决方案


的语法if是:

(if condition expression1 expression2)

条件为真时为表达式1的值,否则为表达式2的值。

在您的函数中,您使用:

(if condition expression1)

这是不允许的。注意,另外三个ifs一个接一个是顺序执行的,实际只使用最后一个的值,作为函数调用的返回值。

解决此问题的一种方法是使用 的“级联” 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)))

推荐阅读