ets:match/2 with maps
Fred Youhanaie
fly@REDACTED
Mon Apr 13 22:40:39 CEST 2020
Thanks, Peti.
I was hoping that I wouldn't have to resort to select.
In my use case the ets:match is called from within a gen_server, and the match pattern, which can be any tuple, is supplied by the client. So, hand-crafted ets:select will not help!
I have now opted for a different data/tuple format.
Cheers,
Fred
On 13/04/2020 19:31, Peti Gömöri wrote:
> Hi Fred,
>
> Unfortunately just with pattern matching it is not possible to exactly match a map, but adding a map_size match condition in the match-spec could work:
>
> 7> ets:select(T, ets:fun2ms(fun({K, #{one := 11}} = O) when map_size(element(2, O)) =:= 1 -> K end)).
> [gamma]
>
> On Mon, Apr 13, 2020 at 2:34 PM Fred Youhanaie <fly@REDACTED <mailto:fly@REDACTED>> wrote:
>
> Hi
>
> I couldn't find any details on map based match patterns!
>
> ETS allows maps as elements of the tuples.
>
> ets:match/2 allows map based match patterns, and returns a result if the pattern map is a subset of the a matched element.
>
> Is there a way of matching a tuple that is not a superset of the map pattern, i.e. only contains the keys in the map pattern?
>
> To clarify, in the following example I would like ets:match/2 to only return [[gamma]].
>
> Many thanks
> Fred
>
> 1> T = ets:new(aaa, []).
> #Ref<0.3164011085.1783496708.202417>
>
> 2> ets:insert(T, {alpha, #{one=>1, two=>2}}).
> true
>
> 3> ets:insert(T, {beta, #{one=>11, two=>12}}).
> true
>
> 4> ets:insert(T, {gamma, #{one=>11}}).
> true
>
> 5> ets:tab2list(T).
> [{gamma,#{one => 11}},
> {alpha,#{one => 1,two => 2}},
> {beta,#{one => 11,two => 12}}]
>
> 6> ets:match(T, {'$1', #{one=>11}}).
> [[gamma],[beta]]
>
More information about the erlang-questions
mailing list