为什么是单臂“如果"?缺少球拍? [英] Why is one-armed "if" missing from Racket?

查看:35
本文介绍了为什么是单臂“如果"?缺少球拍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准方案中是可能的写

(if (> x 2)
    (set! x (- x 1)))

但这在 Racket 中是不可能的——Racket 的 if 总是需要两个手臂.为什么?

but this is not possible in Racket -- Racket's if always requires two arms. Why?

推荐答案

基本原理

if 的单臂变体已从 Racket 中删除,以防止出现错误.

The one-armed variant of if was removed from Racket to prevent bugs.

在函数式代码中,总是使用 if 的双臂变体.

In functional code one always uses the two-armed variant of if.

(if test expr-on-true expr-on-false)

忘记第二个分支 expr-on-false 不会导致语法错误,但会导致运行时错误(表达式将返回 #).

Forgetting the second arm expr-on-false would not lead to a syntax-error, but to a runtime error (the expression would return #<void>).

为了防止函数代码中经常出现的这些错误,决定为 if 的单臂变体引入 when 形式.

To prevent these often occurring bugs in functional code, it was decided to introduce the form when for the one-armed variant of if.

 (when test expr-on-true)

除了防止意外错误之外,新形式还清楚地向代码读者表明,代码依赖于副作用.

Besides preventing accidental bugs, the new form clearly indicated to a reader of code, that the code relies on side effects.

将代码从标准 Scheme 移植到 Racket

如果您尝试在 Racket 中运行 Scheme 代码并看到错误消息

If you try running Scheme code in Racket and see the error message

if: bad syntax (must have an "else" expression)

您必须将 if 表达式重写为 whenunless.

you must rewrite the if expression to when or unless.

简单地重写:

(if test expr1)    to    (when test expr1)

(if (not test) expr1)   to    (unless test expr1).

这篇关于为什么是单臂“如果"?缺少球拍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆