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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With