[erlang-questions] Erlang elseif

Richard O'Keefe <>
Fri Nov 21 03:29:29 CET 2008


> On 2008-11-20 09:41,  wrote:

>> %% The no-good nested case way

Why do you call it "no-good"?
Looks fine to me.
>>
>> 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.

Let's do that with a macro:

-define(If_Member(X, Xs, T, F),
	case lists:member(X, Xs) of true -> T ; false -> F end).

ei(A) ->
     M = ?If_Member(A, ?CAPS,  "Member of capital\n",
         ?If_Member(A, ?SMALL, "Member of small\n",
         ?If_Member(A, ?NUMS,  "Member of nums\n",
                               "Not a member\n"))),
     io:format(M).

It's the same code, but it doesn't look like it.

There's always the higher order approach:

-compile(inline, {if_member/4}).
if_member(X, Ys, T, F) ->
     case lists:member(X, Ys)
       of true  -> T()
        ; false -> F()
     end.

ei(A) ->
     io:format(if_member(A, ?CAPS,  fun() -> "Member of capital\n" end,
      fun() -> if_member(A, ?SMALL, fun() -> "Member of small\n"   end,
      fun() -> if_member(A, ?NUMS,  fun() -> "Member of nums\n"    end,
                                    fun() -> "Not a member\n"      end)
      end) end)).

It's a functional language, the compiler does do inlining, and while
I'm usually a fan of legalistic indenting, readability trumps everything
else.





More information about the erlang-questions mailing list