Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is one-armed "if" missing from Racket?

Tags:

racket

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?

like image 738
soegaard Avatar asked Jun 02 '12 14:06

soegaard


1 Answers

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). 
like image 153
soegaard Avatar answered Sep 24 '22 00:09

soegaard