ðĶConditionals
Last updated
Last updated
When writing functions you may notice that the function behaviors may differ based on the state of the arguments. While and in the function declaration may help to alleviate some of these problems, some derived variables (i.e. variables that are composed of the arguments) cannot be handled through these mechanisms and as such, will require explicit control through conditions.
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
):
You can also use with cases, specifying restrictions on each clause:
If none of the clauses match the given value, then an error is raised.
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:
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.
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.
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: