Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more preferable? Guard or case?

Tags:

erlang

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.
like image 255
goofansu Avatar asked Sep 11 '12 06:09

goofansu


2 Answers

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.

like image 137
evnu Avatar answered Oct 13 '22 17:10

evnu


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.

like image 6
Pascal Avatar answered Oct 13 '22 17:10

Pascal