Search code examples
elixirets

How to call :ets.fun2ms in elixir?


Is it possible? if so, how?

The following code is executed in an IEX.

However, the compiled code generates a runtime error.

 :ets.fun2ms(fn({a,b}) -> a and b end)

The error comes out like this: I want to know how to properly call.

** (exit) exited in: :ets.fun2ms(:function, :called, :with, :real, :fun, :should, :be, :transformed, :with, :parse_transform, :or, :called, :with, :a, :fun, :generated, :in, :the, :shell)
     ** (EXIT) :badarg
 stacktrace:
   (stdlib) ets.erl:554: :ets.fun2ms/1
   test/game/ets_lookup_test.exs:27

Solution

  • No, you can't. At least not with "real functions" like the error says. Elixir functions are defined a bit different than the functions in Erlang and that's why this function does not work. Fortunately, you can accomplish the same using this repository https://github.com/ericmj/ex2ms

    As it is stated in the README:

    iex(1)> import Ex2ms
    iex(2)> fun do { x, y } = z when x > 10 -> z end
    [{{:"$1",:"$2"},[{:>,:"$1",10}],[:"$_"]}]
    iex(3)> :ets.test_ms({ 42, 43 }, v(2))
    {:ok,{42,43}}
    iex(4)> :ets.test_ms({ 0, 10 }, v(2))
    {:ok,false}
    

    The macro Ex2ms.fun/1 does the same as ets:fun2ms/1.

    I hope this helps.