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.
Remember
if
in Erlang has a value to return, and it's an expression. It's not thatif
like in C or Java.If you want to do something for a value, the code should be something like this;
See Section for the
if
expression of Erlang Reference Manual for the further details.Erlang doesn't allow you to have an
if
without atrue
statement option. Whether or not this is something that is a true statement or an actualtrue
is up to you, but it is commonplace to have yourtrue
be theelse
in other languages.See the "What the If?" section on this page for more on this.
First of all, I recommend you to get used to use 'case' statement, because of 'if' conditions restricted to guard expressions:
There is one more way to do conditional execution besides 'if' and 'case' that works starting from R13:
The form for an
if
is: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
if
expression returns the value of the last expression in the body. So theelse
bit in other languages is baked into it. If none of the guards succeeds then anif_clause
error is generated. A common catch-all guard is justtrue
which always succeeds, but a catch-all can be anything which is true.The form for a
case
is: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
case
expression returns the value last expression in the body. If no pattern matches then acase_clause
error is generated.Note that
if
andcase
are 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
.if
is just a degenerate case ofcase
so it inherited it. There is a bit of history ofif
in the Erlang Rationale which you can find on trapexit.org under user contributions.