[erlang-questions] Avoiding case nesting

Gleb Peregud gleber.p@REDACTED
Mon Sep 28 12:38:30 CEST 2009


On Mon, Sep 28, 2009 at 12:23, mayamatakeshi <mayamatakeshi@REDACTED>
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?

One could do this:

    Prefixes = [{"prefix1", fun do_this/1},
                {"prefix2", fun do_that/1},
                {"prefix3", fun do_something/1}],
    catch lists:foldl(fun({Prefix, Fun}, Tail) ->
                  case checkprefix(Prefix, Tail) of
                      {ok, NewTail} ->
                          NewTail;
                      _ ->
                          throw(done)
                  end
              end, String, Prefixes).


P.S. Sorry for HTML formatting


More information about the erlang-questions mailing list