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.<br>
<br>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:<br>
<br>42> e:elseif4($Q).<br>Member of capital<br><br><br>I would appreciate any input on this, even if it means you're bashing all my examples below :-)<br><br>BR,<br>Daniel Rönnqvist<br><br>--- Source code for my test module: ----<br>
<br>-module(e).<br><br>-export([elseif1/1,elseif2/1,elseif3/1,elseif4/1]).<br><br>-define(CAPS, "QWERTY").<br>-define(SMALL, "qwerty").<br>-define(NUMS, "123456").<br><br>%% The wierd not-so-Erlang way<br>
elseif1(A) -> <br> lists:member(A,?CAPS) <br> andalso begin<br> io:format("Member of capital\n"),<br> true<br> end<br> orelse <br> lists:member(A,?SMALL)<br>
andalso begin<br> io:format("Member of small\n"),<br> true<br> end<br> orelse<br> lists:member(A,?NUMS)<br> andalso begin<br> io:format("Member of nums\n"),<br>
true<br> end<br> orelse<br> io:format("Not a member").<br><br>%% The no-good nested case way<br>
elseif2(A) -><br> case lists:member(A,?CAPS) of<br> true -><br> io:format("Member of capital\n");<br> false -><br> case lists:member(A,?SMALL) of<br> true -><br>
io:format("Member of small\n");<br> false -><br> case lists:member(A,?NUMS) of<br> true -><br> io:format("Member of nums\n");<br>
false -><br> io:format("Not a member\n")<br> end<br> end<br> end.<br><br>%% One utterly inefficient tuple way <br>
elseif3(A) -><br> case {lists:member(A,?CAPS),<br> lists:member(A,?SMALL),<br> lists:member(A,?NUMS)} of<br> {true,false,false} -><br> io:format("Member of capital\n");<br>
{false,true,false} -><br> io:format("Member of small\n");<br> {false,false,true} -><br> io:format("Member of nums\n");<br> _ -><br> io:format("Not a member\n")<br>
end.<br><br>%% The list comprehension way<br>
elseif4(A) -><br> case [begin<br> {Name,_} = X,<br> Name<br> end<br> || X <- [{caps, ?CAPS},<br> {small, ?SMALL},<br> {nums, ?NUMS}],<br>
begin<br> {_,List} = X,<br> lists:member(A,List)<br> end] of<br> [caps] -><br> io:format("Member of capital\n");<br> [small] -><br>
io:format("Member of small\n");<br> [nums] -><br> io:format("Member of nums\n");<br> _ -><br> io:format("Not a member\n")<br> end.<br>
<br><br>