[erlang-questions] Pattern Matching Question

Thomas Lindgren <>
Sat Nov 24 09:28:59 CET 2007


--- Esbjörn Dominique <> wrote:

> This reminds me of something that have bothered me
> some times (well,
> not that much): the lack of fall-through á la C
> switch/case. What I
> would like is something like:
> 
> days_in(jan, _);
> days_in(mar, _);
> days_in(may, _);
> days_in(jul, _);
> days_in(aug, _);
> days_in(oct, _) -> 31;
> days_in(dec, _);
> days_in(apr, _);
> days_in(jun, _);
> days_in(sep, _);
> days_in(nov, _) -> 30;
> days_in(feb, common) -> 28;
> days_in(feb, leap) -> 29.
> 
> The motivation is simply to reduce duplication.

You can do it like this:

days_in(Mon, Leap) ->
   if
      Mon == jan ; Mon == .. ; ... -> 31;
      Mon == nov ; ... -> 30;
      Mon == feb, Leap == leap -> 29;
      Mon == feb, Leap == normal -> 28
   end.

(or use other guard operators). You can't do this for
general patterns, of course, because you can't bind
variables in guards.

Another way to reduce duplication is to factor the
common clause bodies into a new function. In this
case, probably not worth it.

Best,
Thomas



      ____________________________________________________________________________________
Be a better sports nut!  Let your teams follow you 
with Yahoo Mobile. Try it now.  http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ



More information about the erlang-questions mailing list