Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching tuples with don't-care variables in Erlang

I am looking for a way to find tuples in a list in Erlang using a partial tuple, similarly to functors matching in Prolog. For example, I would like to following code to return true:

member({pos, _, _}, [..., {pos, 1, 2}, ...])

This code does not work right away because of the following error:

variable '_' is unbound

Is there a brief way to achieve the same effect?

like image 350
Little Bobby Tables Avatar asked Aug 03 '11 07:08

Little Bobby Tables


2 Answers

For simple cases it's better to use already mentioned lists:keymember/3. But if you really need member function you can implement it yourself like this:

member(_, []) ->
    false;
member(Pred, [E | List]) ->
    case Pred(E) of
        true ->
            true;
        false ->
            member(Pred, List)
    end.

Example:

>>> member(fun ({pos, _, 2}) -> true; (_) -> false end, [..., {pos, 1, 2}, ...]).
like image 117
hdima Avatar answered Sep 26 '22 17:09

hdima


Use lists:keymember/3 instead.

like image 37
Hynek -Pichi- Vychodil Avatar answered Sep 24 '22 17:09

Hynek -Pichi- Vychodil