4
votes

I have cached a bunch of postcode and lat-long values using erlangs ets functionality.

Picture the following...

iex()> :ets.new(:postcode_cache, [:named_table])
:postcode_cache
iex()> :ets.insert(:postcode_cache, [{"OX495NU", "latlongvalue"},{"M320JG", "latlongvalue"}])
true

This is similar to the ets table I have created in my application. I want to create a function that only selects entries from the cache where the postcode contains a substring of what a user has entered. Is there any way to do this, and if so, how would I implement this functionality?

(In the future I may like to only select values that are within a certain distance using the lat-long value but that is beyond the scope of this question).

Just for clarity, the table is similar to the following elixir list...

iex()> postcode_list = [{"OX495NU","latlong"}, {"M320JG", "latlong"}]

The functionality that I would like to replicate with ets is something like this...

iex()> Enum.filter(list, fn({postcode, _}) -> if String.contains?(postcode, "OX49") end)
[{"OX495NU", "latlong"}]
1

1 Answers

2
votes

One cannot invoke arbitrary functions in matches, but here you have a match on hand that can be used with :ets.foldl/3:

:ets.foldl(fn
  {<<"0X49", _ :: binary>>, "latlong"} = n, acc -> [n | acc]
  _, acc -> acc
end, [], :named_table)