[erlang-questions] case or clause

Richard Carlsson <>
Thu Jan 8 23:04:39 CET 2009


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



More information about the erlang-questions mailing list