When to when
Yesterday we mentioned the when
function as an alternative to if
.
It might seem like a weaker form, so why would you use it?
It turns out that when
is is really useful for a few reasons.
You might end up using it more than if
!
Argument Validation🔗
One particularly good place to use when
is for argument validation.
Typically when an argument is not valid, you'll want to throw an error.
defn double-sqrt(x):
when not(number?(x)):
die: "x must be a number"
when x < 0:
die: "x must be positive"
=>: sqrt(x) * 2
An if
would be inappropriate here, because when the condition is false,
there's nothing to do.
when Returns nil🔗
Remember that YS is a functional language.
Therefore the when
function always has to return a value.
If the condition is false, it returns nil
.
What if you need an if
call that returns a number or a nil?
You can just use when
to do that.
x =:
if a > b:
then: a + b
else: nil
# Some thing as above:
x =:
when a > b: a + b
when Has do Semantics🔗
Remember how we used then
and else
in if
, when we needed to do more than
one thing?
The then
and else
clauses compiled to a do
form.
Well when
always lets you do that.
when a < 0:
say: 'a'
say: 'is'
say: 'negative'
when Has a Friend🔗
There's a function called when-not
that is the opposite of when
.
Remember this from above?
defn double-sqrt(x):
when not(number?(x)):
die: "x must be a number"
We could also write that as:
defn double-sqrt(x):
when-not number?(x):
die: "x must be a number"
when
will I see you again?🔗
Probably tomorrow.