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?
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.
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