ðĶConditionals
case
case
is used to compare a given value against many patterns until a matching one is found. This is most similar to switch
statements in other languages:
If a pattern contains a reference to a variable outside of the case
, you need to use the pin operator ^
which "locks" in the variable at the time of use, preventing it from being re-assigned (like in the above example with x
):
If none of the clauses match the given value, then an error is raised.
if
if
is relatively straightforward and is pretty much the same as the other languages:
There is no explicit elif
so if you have multiple if
statements, you will have to nest them as such:
Like functions, you can also write the if
statements as one-liners:
cond
Notice that when using if
, the lack of an explicit elif
causes your code to adopt an arrowhead style. This is can make your code look messy. This is where cond
comes in. cond
is the same as flattening the nested if
statements:
The final true
clause is used as the "default" case. This is because each clause in cond
is supposed to evaluate to a boolean.
unless
A final conditional we are introducing is the unless
conditional which works as the opposite of if
. The statement given to unless
must be false for the body to run.
Returning conditionals
Everything in Elixir is an expression. This means that even the conditionals are just expressions. This allows the conditionals to be assigned to variables or returned from functions:
Last updated