Style 1:
a(X) when X>1 ->
...omitted;
a(X) when X ->
...omitted.
Style 2
a(X) ->
case X>1 of
true-> ...ommited;
false-> ...ommited
end.
====Update===
As @rviding said, I update the comparison as following:
Style 1:
a(X) when X>1 ->
...omitted;
a(X) ->
...omitted.
Style 2
a(X) ->
case X>1 of
true-> ...ommited;
false-> ...ommited
end.
Learn You Some Erlang's section on function syntax states that function clauses and case statements are basically the same, except for one difference: pattern matching in clauses can handle more than one pattern, whereas a case statement can only handle one statement.
Apart from that, I believe it is a matter of taste. I tend to use different function clauses when the cases are really distinct (as in: the complete function will behave differently), and I use case statements when I want the code to diverge and be merged afterwards again, e.g. to calculate the value for a variable based on an expression.
Edit
As pointed out by RobertAloi in the comments below, you are not really restricted when using case .. of
. Also, as rvirding wrote, the compiler does some optimization when wrapping different expressions in a tuple to allow matching against them.
You should also consider that testing the result of a BIF has not the exact same behavior in a guard than inside a function.
I learned this recently, for example (length(L) > -1)
crashes inside a function but not in a guard when L is an improper list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With