The form for an if
is:
if
<guard 1> -> <body1> ;
<guard 2> -> <body2> ;
...
end
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 the else
bit in other languages is baked into it. If none of the guards succeeds then an if_clause
error is generated. A common catch-all guard is just true
which always succeeds, but a catch-all can be anything which is true.
The form for a case
is:
case <expr> of
<pat 1> -> <body1> ;
<pat 2> -> <body2> ;
...
end
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 a case_clause
error is generated.
Note that if
and case
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 for case
. if
is just a degenerate case of case
so it inherited it. There is a bit of history of if
in the Erlang Rationale which you can find on trapexit.org under user contributions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…