[erlang-questions] Re: Correct syntax of a case clause

Bryan Fink bryan.fink@REDACTED
Mon Jun 15 19:36:34 CEST 2009


On Mon, Jun 15, 2009 at 1:17 PM, info<info@REDACTED> wrote:
> Hi All,
>
> Hey that was my question .... and you wander from my subject !
> I gave an example but don't try to solve this example !!
>
> case Expr of
> pattern1 -> do_1;
> pattern2-> do_2;
> pattern3 -> do_3;
> ...
> end
>
> The question was "is it possible to group two patterns in a case ?"

Your answer was given by Martin Engström yesterday.  Use a "when"
clause in your patterns.

case Expr of
    Pat1 when Pat1 =:= pattern1; Pat1 =:= pattern2 ->
        do_1;
    pattern3 ->
        do_3
end

Another pattern that has been demonstrated on this list many times is
breaking the classification and execution steps into different
functions:

case classify(Expr) of
    do_1_pattern -> do_1;
    do_3_pattern -> do_3
end

classify(pattern1) -> do_1_pattern;
classify(pattern2) -> do_1_pattern;
classify(pattern3) -> do_3_pattern.

This works well when there's some more-involved computation needed for
choosing the case branch (that is, when Expr is not a simple atom to
match against).  A similar 'when' clause can be used on the classify/1
function.

-Bryan


More information about the erlang-questions mailing list