Transforming funs to match specifications

How can I get Elixir to help me with generating match specifications from funs. There is an Erlang function :ets.fun2ms/1 which can do this. Sort of anyway, in that the Erlang compiler actually tranforms this to the match specification at compile time. Can I tell the Elixir compiler to do this tranformation?

There are no problems in using match specifications explicitly in Elixr of course as they are just data structures, it doing the transformation I am after.

1 Like

There is no way to have ets:fun2ms/1 in Elixir, as Elixir disallows parse transforms. However you can use macros to achieve the same thing.

2 Likes

There is this old post…

Maybe this package can help?

2 Likes

There is also @ityonemo’s

:ets matchspec helper library for elixir. Exposes the fun2ms/1 macro which transforms elixir-style function code into ets matchspecs.

iex> require MatchSpec
iex> MatchSpec.fun2ms(fn {key, value} when key === :foo -> value end)
[{{:"$1", :"$2"}, [{:"=:=", :"$1", {:const, :foo}}], [:"$2"]}]

fun2ms and ms2fun for elixir! Advent of code day 22 (remastered)

5 Likes

Thanks for the suggestions. Why does the Elixir compiler disallow parse transforms?

The problm is I have another issue than just doing it from Elixir :smiley: and that is I want to do it from LFE (Lisp Flavoured Erlang) as well. And there I have records which Elixir doesn’t, and these 2 packages, don’t really support. The LFE compiler makes full use of the Erlang compiler so it just translates all record operations into the record expressions in the Erlang AST.

I am also looking at doing it in a nice way using the modules in Erlang but without parse transforms, which will be the last option.

Here is discussion

Writing such macro also shouldn’t be really hard there, so it can go that route.