[erlang-questions] case or clause

Johnny Billquist bqt@REDACTED
Thu Jan 8 23:51:38 CET 2009

Sten Kvamme wrote:
> tor 2009-01-08 klockan 23:04 +0100 skrev Richard Carlsson:
>> Sten Kvamme wrote:
>>> I got the question the other day about erlang best practize, to use case
>>> or clause? (don't know if clasuse is the correct erlang name, but you
>>> know -- in a Prolog-way).
>>> Is erlang better/faster/leaner if I implement several "prolog" clauses
>>> as a case in a clause, or is it better/faster/leaner to reduce the use
>>> of case to situations when local variables in a clause is used in the
>>> case statement?
>>> Or is it just a matter of 'taste'?
>> You presumably mean the difference between
>>    f(Pattern1, ..., PatternN) -> ...;
>>    ...
>>    f(Pattern1, ..., PatternN) -> ....
>> and
>>    f(X) ->
>>      case X of
>>        Pattern1 -> ...;
>>        ...
>>        PatternN -> ...
>>      end.
>> In efficiency terms, there is no real difference. (If there is one,
>> it should be considered a compiler problem that might be corrected
>> at any time - do not waste your time on such microoptimizations.)
>> Oh, and 'if' switches are no different - they're really a 'case'.
>> So it's mostly a matter of taste. If your switch makes sense on its
>> own, i.e., you can give it a reasonably straightforward name, then
>> by all means break it out as a function - it will make the code
>> easier to read and make it easier for you to see when there is
>> common functionality that could be reused rather than copy-pasted.
>>      /Richard
> Ok, and if I'm using several clauses, is it like it is in Prolog a good
> idea to put the clauses that match most often at the top?

Don't make the mistake of thinking like Prolog when you write Erlang, or 
you'll be severly bitten.
Erlang will *not* match several clauses. It will stop matching at the 
first "hit". No backtrace like in Prolog.
And it does the matches in the same order as the clauses are written in 
the source. Top down...


More information about the erlang-questions mailing list