37

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 requires two arms. Why?

1 Answer 1

61

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.