The if-else statement (a.k.a., conditional statement, conditional expression, etc.) is a basic feature of programming languages. In the languages I first learned (BASIC, C, Python), I thought if-else was a monolithic thing. Many languages have an elseif statement, and some languages (e.g., C, Ruby) have a switch or case statement that takes care of complicated if-elseif-elseif-elseif… situations. All of these are just syntactic sugar for a chain of if-else statements, which reinforced my idea that if-else was monolithic.
I was very confused when, while learning about Haskell, that Haskell’s if always has an else. The idea, in Haskell, is that everything that happens in the program is about the movement of information, not the execution of actions. It doesn’t make sense to say that variable X should be foo if Y is true, but it’s not anything if Y is false.
I was, at first, confused to see that Racket has an
[if](http://docs.racket-lang.org/reference/if.html) and a
[when](http://docs.racket-lang.org/reference/when_unless.html), which are different things. In this case,
if is like Haskell’s if, which always comes with an else, while
when is an if that never has an else.
When looking at some of my work-a-day Python code, I discovered that I use Python’s if both as
when. For example, some of my if statements look like:
if switcher_thingy: output_variable = value_when_switch_is_true else: output_variable = value_when_switch_is_false
I would use this kind of if-else when, say, I wanted to use either a default value or compute a new value from scratch. Other if statements look like:
if some_switch_about_program_execution: take_some_action()
I would use this kind of if-else when, say, I wanted to output some extra when the program is running in a verbose mode, or I would shuffle entries in an array when I wanted to randomize the data.
The first kind of if is exactly what Racket’s
if is for. The second is exactly what Racker’s
when is for. Maybe it seems excessive to put more syntax into the program, but I think it’s helpful to understand that
if is basically a function that takes a Boolean and two other values, and returns one of those two values, while
when is a subroutine that takes an action only when some boolean is true.