Is there an idiomatic way to organize functions in Erlang?

For functions where the order of sentences is unimportant, is it the base case of the latter:

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

Or the base case:

 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 that the convention is basic. Is this the preferred style? Is there a reason for this, or is it the way it is?

+4
source share
3 answers

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

Since the integer 0 can correspond to the pattern N, the condition of the constant 0 will never be reached if it occurs after.

This is an ordered aspect of pattern matching that you should think about when writing feature sentences, case sentences, or any other such sequence of potential matches.

+5
source

It has semantic meaning, how sentences are ordered. Since patterns are undertaken in sequential order.

I tend to put basic boxes first, as I think this makes it more readable. Already know the basic cases when reading the recursive part.

Sometimes I get the feeling that some code first uses the most common template to keep the most common case from having to test templates that are unlikely to match.

+4
source

With [|] and [] I always put the base case (s), and the zero register is the last, as in your first case. I think this is much clearer and more natural. One reason for the opposite may be that it more closely resembles a more general pattern matching, when you first come across more specific cases to catch; here [] will be as a more specific case. Just guess though.

+3
source

All Articles