Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic way to order function clauses in Erlang?

Tags:

erlang

For functions where the ordering of the clauses is unimportant, is it base case last:

all(Pred, [Head|Tail]) ->
  case Pred(Head) of
    true -> all(Pred, Tail);
    false -> false
  end;
all(Pred, []) when is_function(Pred, 1) -> true.

Or base case first:

all(Pred, []) when is_function(Pred, 1) -> true;
all(Pred, [Head|Tail]) ->
  case Pred(Head) of
    true -> all(Pred, Tail);
    false -> false
  end.

From looking at the source code in the standard library, it seems the convention is base case last. Is that the preferred style? Is there a reason for it, or is it just the way it is?

like image 446
pjb3 Avatar asked Dec 17 '22 04:12

pjb3


2 Answers

Only the second case will work, as cases are matched in order.

Since the integer 0 is able to match the pattern N, the constant 0 clause would never be reached if it came after.

It is that ordered aspect of pattern-matching which you should think about when writing function clauses, case clauses, or any other such sequence of potential matches.

like image 56
Justin Sheehy Avatar answered Mar 07 '23 18:03

Justin Sheehy


It has semantic meaning how the clauses are ordered. Since patterns are attempted in sequential order.

I tend to put base-cases first since I think it makes it more readable. To already know the base cases when reading the recursive part.

Sometimes I get the feeling that some code have put the most common pattern first, to save the most common case from having to test patterns that it will not likely match.

like image 34
Christian Avatar answered Mar 07 '23 18:03

Christian