In Erlang, is there a way to pattern match against an enumerated set of atoms?

erlang, pattern-matching

Solution

Currently there is no direct way to specify lists of atoms as pattern.

In your case you could use a guard but its hardly shorter

b_and(true, true) -> true;
b_and(A, B) when A =:= true or A =:= false,
                 B =:= true or B =:= false ->
    false.

Btw one would often leave the error clause off when it would be a error to call the function with anything else.

You could use this parse transform https://github.com/mad-cocktail/gin which woul give you a in() form for the guards. The question is if it is worth it, just for such a little and not very often used feature having a parse transform seems a bit heavyweight.

Problem

I'm currently picking up Erlang, and its pattern matching is one of the coolest things I've seen in awhile. One little toy function I've come up with in my exercises is as follows: ``` b_and(true, true) -> true; b_and(true, false) -> false; b_and(false, true) -> false; b_and(false, false) -> false; b_and(_, _) -> {error, invalid_object}. ``` I was wondering, though, is there syntax for telling a Variable in a pattern to accept only from a set of enumerated atoms? That way, I could shorten it to something like this: ``` b_and(true, true) -> true; % We've already satisfied the only true case b_and(ENUM(true, false), ENUM(true, false)) -> false; b_and(_, _) -> {error, invalid_object}. ``` I've looked through the docs on pattern matching, but I couldn't find anything like this.

Original source