[erlang-questions] Avoiding case nesting

Ulf Wiger ulf.wiger@REDACTED
Mon Sep 28 14:10:03 CEST 2009


I would probably use lists:dropwhile/2 in this
situation, at least if you do not expect to take action
in the case where it isn't a prefix.

List = prefixes(),
case lists:dropwhile(fun(P) -> not_prefix(P, String) end, List) of
     [] ->
        % no prefix
        ...
     [Prefix|_] ->
        Tail = lists:nthtail(length(Prefix), String),
        do_that(Tail)
end.

BR,
Ulf W

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
> 


-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com


More information about the erlang-questions mailing list