Search code examples
erlangets

ets:match does not return expected value


I'm having trouble with ets:match. In the following code I expect the ets:match to return 1 found value, but none is returned. Why ?

1> T = ets:new(xxx, []).
16400
2> ets:insert(T, {a, b, c, d}).
true
3> ets:match(T, {'_', '_', '_', '_'}).
[[]]

Solution

  • You probably want ets:match_object/2 instead:

    > ets:match_object(T, {'_', '_', '_', '_'}).
    [{a,b,c,d}]
    

    When using ets:match/2, the pattern should include some atoms like '$1', '$2' and so on. The result will be a list of lists, where each sublist will contain the corresponding elements in the order given by the magic atoms. For example, to get the last three elements in reverse order:

    > ets:match(T, {'_', '$3', '$2', '$1'}).
    [[d,c,b]]
    

    Since you didn't use any such atoms in your match, zero elements are returned for each match; thus the list containing one empty list, [[]].