[erlang-questions] Idiom for multiple case matches

Robert Virding rvirding@REDACTED
Fri Nov 7 11:14:49 CET 2008


A reasonable way of doing it would be:

case is_vowel(Char) of
    true -> ... ;
    false -> ...
end

with

is_vowel($a) -> true;
...
is_vowel(_) -> false.

It is clear what you are doing and it is easy to extend is_vowel/1 with new
rule when more vowels are added. It also has the benefit of abstracting out
the tests and making sure that all vowel testing in the code will always be
correct.

Robert

2008/11/5 Colm Dougan <colm.dougan@REDACTED>

> Hi,
>
> I often find myself writing code like this :
>
> (Note: I'm only using vowels as a contrived example here).
>
>   case Char of
>     Vowel when Vowel =:= $a;
>     Vowel =:= $e;
>     Vowel =:= $i;
>     Vowel =:= $o;
>     Vowel =:= $u ->
>        io:format("Handling vowel~n");
>     _ ->
>        io:format("Not a vowel~n")
>   end.
>
> Is there any better idiom for this?  It usually becomes long-winded.
> For example, it would seem ideal to be able to do this :
>
>   case Char of
>     $a; $e; $i; $o; $u ->
>         io:format("Handling vowel~n");
>    _ ->
>        io:format("Not a vowel~n")
>   end.
>
> Yeah I realise I could write function either with one massive guard
> statement or something like this :
>
> handle_char($a) -> handle_vowel($a);
> handle_char($e) -> handle_vowel($e);
> handle_char($i) -> handle_vowel($i);
> handle_char($o) -> handle_vowel($o);
> handle_char($u) -> handle_vowel($u);
> handle_char(Char) -> handle_non_vowel(Char).
>
> .. which is a nice approach but sometimes an inline case statement is
> all you want.
>
> Thanks,.
> Colm
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081107/ddb4dfb9/attachment.htm>


More information about the erlang-questions mailing list