[erlang-questions] Feedback on the code, please? :)
Richard Carlsson
carlsson.richard@REDACTED
Tue Jul 26 10:47:28 CEST 2011
On 07/26/2011 12:34 AM, Peter Mechlenborg wrote:
> One comment on your code. I always put the function clauses for the
> base-case at the top and I think this is the norm. Others will
> hopefully correct me if I am mistaken.
Efficiency-wise it's better to leave the base cases last. (If the
clauses may safely be reordered, the compiler might fix this for you,
but you can't rely on it in general.)
Clauses are tried in order, so if you loop over a list of N elements,
the base case will be true only in the last case, and in all the other
N-1 cases, you will waste a little time checking "is this an empty
list... nope... is it a nonempty list... yes - OK, let's run the second
clause".
The exception is if you only test in the base case and have a catch-all
clause (i.e., without any test) for the recursive case; e.g., "is X
zero... no... OK, let's run the second clause".
And if you find that putting the base cases last makes them end up too
far down on the page, and too far away from the head of the recursive
clause, it's a sign that your clause body for the recursive case is way
too long and should be broken out into a separate function.
/Richard
More information about the erlang-questions
mailing list