I have 2 parts of code I want to execute. Both are conditionals
if Value1 < N do something
else if Value1 >= N do something
if Value2 < N do something
else if Value2 >= N do something
I want at one statement of each to execute.
How does the if work in erlang? there is no else. I use multiple guards, but that looks like I have 4 if statements. in groups of 2.
if some condition
code;
if other condition
code
end.
I get a syntax error.
The form for an
ifis:It works trying the guards in if-clauses in top-down order (this is defined) until it reaches a test which succeeds, then the body of that clause is evaluated and the
ifexpression returns the value of the last expression in the body. So theelsebit in other languages is baked into it. If none of the guards succeeds then anif_clauseerror is generated. A common catch-all guard is justtruewhich always succeeds, but a catch-all can be anything which is true.The form for a
caseis:It works by first evaluating and then trying to match that value with patterns in the case-clauses in op-down order (this is defined) until one matches, then the body of that clause is
evaluated and the
caseexpression returns the value last expression in the body. If no pattern matches then acase_clauseerror is generated.Note that
ifandcaseare both expressions (everything is an expression) so they both must return values. That is one reason why there is no default value if nothing succeeds/matches. Also to force you to cover all options; this is especially important forcase.ifis just a degenerate case ofcaseso it inherited it. There is a bit of history ofifin the Erlang Rationale which you can find on trapexit.org under user contributions.