[erlang-questions] Erlang elseif

kdronnqvist@REDACTED kdronnqvist@REDACTED
Thu Nov 20 13:10:21 CET 2008


Thanks for your solutions, they give me good insight in how the Erlang world
would solve this. I have one more way of solving this that I think is kind
of clean and it would be efficient because the lists:member() would need to
be evaluated once a match is found.

elseif5(A) ->
    try
        lists:member(A,?CAPS) andalso throw(caps),
        lists:member(A,?SMALL) andalso throw(small),
        lists:member(A,?NUMS) andalso throw(nums),
        throw(none)
    catch
        throw:caps -> io:format("Member of capital\n");
        throw:small -> io:format("Member of small\n");
        throw:nums -> io:format("Member of nums\n");
        throw:none -> io:format("Not a member\n");
        X:Y -> io:format("Bad exception ~p:~p\n",[X,Y])
    end.

However, some might think this is the wrong way of handling exceptions. What
do you think?

BR,
Daniel Rönnqvist


2008/11/20 Richard Carlsson <richardc@REDACTED>

> kdronnqvist@REDACTED wrote:
> > I wrote a couple of examples how to solve this but none of them really
> > feels right, the logic in what I'm trying to do is really REALLY not
> > that complicated. The functions takes an argument and prints something
> > based on what list the argument is a member of (if any). Like this:
> >
> > 42> e:elseif4($Q).
> > Member of capital
> >
> > I would appreciate any input on this, even if it means you're bashing
> > all my examples below :-)
>
> If you want a reusable pattern, rather than a one-off hack,
> the best thing is to start by separating the logic and the
> side effects (as in your 4th example).
>
> member_of(X, Lists) ->
>  case lists:dropwhile(fun ({A,L}) -> not lists:member(X,L) end, Lists) of
>    [{A,_}|_] -> A;
>    [] -> none
>  end.
>
> print_class(C) ->
>  case member_of(C, [{caps, ?CAPS}, {small, ?SMALL}, {nums, ?NUMS}]) of
>     caps -> io:format("Member of capital\n");
>     small -> ...;
>    nums -> ...;
>    none -> ...
>  end.
>
>
> For one-off things, prefer the threaded functions solution if there
> are more than 2 levels.
>
>    /Richard
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081120/07a48f3d/attachment.htm>


More information about the erlang-questions mailing list