[erlang-questions] Avoiding case nesting

Jayson Vantuyl kagato@REDACTED
Mon Sep 28 12:38:59 CEST 2009


I believe that you can still use pattern matching.  Something like:

> case String of
>   [ FirstPrefix | Tail ] -> do_this(Tail);
>   [ SecondPrefix | Tail ] -> do_that(Tail);
>   ...
>   _ -> didnt_match
> end.

Although, if you have a variable number of prefixes, it may be better  
do this with recursion and a list of {Prefix,HandlerFunc}.

Also, if you do have to work with nested cases, this article might  
help you make them easier to debug:

> http://www.trapexit.org/Nested_Cases


Good luck!

On Sep 28, 2009, at 3:23 AM, mayamatakeshi wrote:

> Hello,
> newbie question:
> Suppose that I need to check if a certain string starts with one of  
> several
> prefixes.
> So I write a checkprefix function that return the tail after the  
> prefix if
> it is found.
> If the prefixes were known at compile time, I could use function  
> pattern
> matching and have a very clean code for this, however, the prefixes  
> are
> loaded from configuration file and I ended up writing something like  
> this:
>
> case checkprefix(FirstPrefix, String) of
>    {ok, Tail} ->
>        do_this(Tail);
>    _ ->
>        case checkprefix(SecondPrefix, String) of
>            {ok, Tail} ->
> `                do_that(Tail);
>            _ ->
>                case checkprefix(ThirdPrefix, String) of
>                    and so on...
>
> So, is there a way to avoid this cascading of case expressions?
>
> regards,
> takeshi

-- 
Jayson Vantuyl
kagato@REDACTED







More information about the erlang-questions mailing list