Why is one-armed “if” missing from Racket?

前端 未结 1 1909
滥情空心
滥情空心 2020-12-09 15:15

In standard Scheme it is possible to write

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

but this is not possible in Racket -- Racket\'s if always r

相关标签:
1条回答
  • 2020-12-09 15:47

    Rationale

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

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

    (if test expr-on-true 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>).

    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.

    Porting code from standard Scheme to Racket

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

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

    you must rewrite the if expression to when or unless.

    Simply rewrite:

    (if test expr1)    to    (when test expr1)
    

    and

    (if (not test) expr1)   to    (unless test expr1).
    
    0 讨论(0)
提交回复
热议问题