Correct syntax of a case clause

John Haugeland stonecypher@REDACTED
Mon Jun 15 08:51:50 CEST 2009


> How to formulate a "complex pattern" in a case clause ?
>
> case Expr of
> a,b -> block1;        % if Expr = a or b then block1
>   c -> block2         % if Expr = c then block2
> end
>
> (a,b) gives an error
> What is the correct syntax ?

Several methods are available.  They have different costs.

The most natural expression is case Foo of a -> X; b -> X; c -> Y end.
 However, if you have more than a few things in your list of a,b, that
can get tedious to maintain and update, especially given that Erlang
doesn't have something resembling fallthrough.

You could do case Foo of c -> Y; _ -> X end; however, that has
significantly different behavior when handling data outside a,b,c.
That will fail to crash when provided with bad data, and that's
probably a very high cost.

You could have the function return a list, then test for membership,
which is easy to maintain and easy to update, but wastes a fair amount
of CPU time.

My opinion is that the first of the three is the strongest general
answer.  It does imply slightly heavier code which fails DRY and which
is a trivial maintenance increase.  If you're writing something which
is expected to be only called once an hour or less, then the third
option is probably the best, as it involves the least long-term
maintenance and is clearest, though in engineering terms it's kind of
stupid.  If you don't care about changing how the code reacts to
unexpected values, then the second strategy is the clear winner.


More information about the erlang-questions mailing list