Checking for membership in an Erlang guard

感情迁移 提交于 2020-01-02 03:39:28

问题


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?


回答1:


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



回答2:


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.



回答3:


The easiest thing is to consider guards as a part of pattern matching, the part which cannot, or is difficult to, express in the pattern itself. So a guard is a sequence of guard tests and not boolean expressions. The original guard syntax made it easier to see the difference but now they look like boolean expressions, which they are not.



来源:https://stackoverflow.com/questions/6927632/checking-for-membership-in-an-erlang-guard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!