开发者

Is there an idiomatic way to order function clauses in 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 standa开发者_如何学运维rd 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?


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.


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.


With [|] and [] I always put the base case(s) first, and the nil case(s) last, as in your first case. I think this much clearer and more natural. One reason for doing the opposite may be that it more resembles the more general pattern matching where you have the more specific cases first so as to catch them; here [] would be like the more specific case. Just guessing though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜