如何在Scheme中编写if-else语句?

时间:2020-04-19 05:22:10

标签: functional-programming scheme

我想将这些double if语句转换为if-else语句。

(if (symbol? x)
            (begin
              (display "ONE")
            )
    )
(if (integer? x)
            (begin
              (display "TWO")
            ) 
)

不使用球拍。

1 个答案:

答案 0 :(得分:2)

仅使用标准Scheme,为此,我们有cond

(cond ((symbol? x) (display "ONE"))
      ((integer? x) (display "TWO"))
      (else (display "OTHER")))

如果您有某种限制,并且必须使用if,我们可以将其嵌套:

(if (symbol? x)
    (display "ONE")
    (if (integer? x)
        (display "TWO")
        (display "OTHER")))

我们可以删除begin表达式。在cond版本中,它们是完全不需要的;而在嵌套if版本中,当其中只有一个表达式时,则不需要。

在两个版本中,我都添加了一个else条件,因为某些Scheme风格使它成为强制性的,而且还是最佳实践。

相关问题