Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for membership in an Erlang guard

What is the simplest way to write an if statement in Erlang, where a part of the guard is member(E, L), i.e., testing if E is a member of the list L? The naive approach is:

if 
  ... andalso member(E,L) -> ...
end

But is does not work becuase, if I understand correctly, member is not a guard expression. Which way will work?

like image 366
Little Bobby Tables Avatar asked Aug 03 '11 13:08

Little Bobby Tables


2 Answers

Member functionality is, as you say, not a valid guard. Instead you might consider using a case pattern? It's possibly to include your other if-clauses in the case expression.

case {member(E,L),Expr} of
  {true,true} -> do(), is_member;
  {true,false} -> is_member;
  {false,_} -> no_member
end
like image 148
D.Nibon Avatar answered Sep 29 '22 02:09

D.Nibon


It is not possible to test list membership in a guard in Erlang. You have to do this:

f(E, L) ->
    case lists:member(E, L) of
        true  -> ...;
        false -> ...
    end.
like image 36
Adam Lindberg Avatar answered Sep 29 '22 01:09

Adam Lindberg