Matching tuples with non-care variables in Erlang

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

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

This code does not work right away due to the following error:

variable '_' is unbound

Is there a short way to achieve the same effect?

+5
source share
6 answers

For simple cases, it is better to use the lists already mentioned : keymember / 3 . But if you really need a function member, you can implement it yourself as follows:

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}, ...]).
+3
source

, :

-define(member(A,B), length([0 || A <- B])>0).

?member({pos, _, _}, [{width, 17, 42}, {pos, 1, 2}, totally_irrelevant]).

( ), .

, , "length" :

-define(filter(A,B), [_E || A =_E <- B]).
+2

, :

Matches = [ Match || {Prefix, _, _} = Match <- ZeList, Prefix == pos].

0

, '_' raw _. , :

member(X, List) when is_tuple(X), is_list(List) ->
    member2(X, List).

% non-exported helper functions:

member2(_, []) ->
    false;
member2(X, [H|T]) when not is_tuple(H); size(X) =/= size(H) ->
    member2(X, T);
member2(X, [H|T]) ->
    case is_match(tuple_to_list(X), tuple_to_list(H)) of
        true -> true;
        false -> member2(X, T)
    end.

is_match([], []) ->
    true;
is_match(['_'|T1], [_|T2]) ->
    is_match(T1, T2);
is_match([H|T1], [H|T2]) ->
    is_match(T1, T2);
is_match(_, _) ->
    false.

:

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

{A, A, '_'} (, ), , .

, ('$1', '$2' ..) - is_match , , , '_'.

, . , , , , , , . , .

0

ets:match:

6> ets:match(T, '$1'). % Matches every object in the table
[[{rufsen,dog,7}],[{brunte,horse,5}],[{ludde,dog,5}]]
7> ets:match(T, {'_',dog,'$1'}).
[[7],[5]]
8> ets:match(T, {'_',cow,'$1'}).
[]
0

All Articles