[erlang-questions] Erlang elseif
kdronnqvist@REDACTED
kdronnqvist@REDACTED
Thu Nov 20 09:41:57 CET 2008
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").
%% The no-good nested case way
elseif2(A) ->
case lists:member(A,?CAPS) of
true ->
io:format("Member of capital\n");
false ->
case lists:member(A,?SMALL) of
true ->
io:format("Member of small\n");
false ->
case lists:member(A,?NUMS) of
true ->
io:format("Member of nums\n");
false ->
io:format("Not a member\n")
end
end
end.
%% One utterly inefficient tuple way
elseif3(A) ->
case {lists:member(A,?CAPS),
lists:member(A,?SMALL),
lists:member(A,?NUMS)} of
{true,false,false} ->
io:format("Member of capital\n");
{false,true,false} ->
io:format("Member of small\n");
{false,false,true} ->
io:format("Member of nums\n");
_ ->
io:format("Not a member\n")
end.
%% The list comprehension way
elseif4(A) ->
case [begin
{Name,_} = X,
Name
end
|| X <- [{caps, ?CAPS},
{small, ?SMALL},
{nums, ?NUMS}],
begin
{_,List} = X,
lists:member(A,List)
end] of
[caps] ->
io:format("Member of capital\n");
[small] ->
io:format("Member of small\n");
[nums] ->
io:format("Member of nums\n");
_ ->
io:format("Not a member\n")
end.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081120/4b4244e8/attachment.htm>
More information about the erlang-questions
mailing list