[erlang-questions] Erlang elseif

attila.rajmund.nohl@REDACTED attila.rajmund.nohl@REDACTED
Thu Nov 20 10:26:42 CET 2008


On Thu, 20 Nov 2008, kdronnqvist@REDACTED wrote:

> Hi everyone I just joined the list and tried to search for information about
> this but I could not find anything that answered my question. The thing is
> that I want a general way to branch the execution of my code based on the
> result on an expression. Very similar to how if works but I want to be able
> to test expressions and not only guards. If you're thinking "then you have
> case" now look below at function elseif2() and you'll see my point.
>
> 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 :-)
>
> BR,
> Daniel Rönnqvist
>
> --- Source code for my test module: ----
>
> -module(e).
>
> -export([elseif1/1,elseif2/1,elseif3/1,elseif4/1]).
>
> -define(CAPS, "QWERTY").
> -define(SMALL, "qwerty").
> -define(NUMS, "123456").
>
> %% The wierd not-so-Erlang way
> elseif1(A) ->
>    lists:member(A,?CAPS)
>        andalso begin
>                    io:format("Member of capital\n"),
>                    true
>                end
>        orelse
>        lists:member(A,?SMALL)
>        andalso begin
>                    io:format("Member of small\n"),
>                    true
>                end
>        orelse
>        lists:member(A,?NUMS)
>        andalso begin
>                    io:format("Member of nums\n"),
>                    true
>                end
>        orelse
>        io:format("Not a member").

What I see in lots of code is this:
elsif(A) ->
 	maybe_caps(lists:member(A, ?CAPS), A).

maybe_caps(true, _) ->
 	io:format("Member of capital\n");

maybe_caps(false, A) ->
 	maybe_small(lists:member(A, ?SMALL), A).

maybe_small(true, _) -.
 	io:format("Member of small\n");

maybe_small(false, A) ->
 	maybe_num(lists:member(A, ?NUMS)).

maybe_num(true) ->
 	io:format("Member of nums\n");

maybe_num(false) ->
 	io:format("Not a member").

 				Bye,NAR
-- 
"Beware of bugs in the above code; I have only proved it correct, not
  tried it."



More information about the erlang-questions mailing list