Creating Anonymous Functions Using Macros

I am contacting to create an API where an anonymous function consists of macros, for example

transform [x, y], do: x + y
transform x,      do: x

should be used transform headand body[:do]how the head and body of the anonymous function. For example, the above macro calls. The above example should be collected in:

fn [x, y] -> x + y; x -> x end

Using unquote fragments, it’s easy to create a new named function defs, but not new anonymous functions:

iex> val = 1
iex> fn() -> unquote(val) end
** (CompileError) iex:99: unquote called outside quote
(elixir) src/elixir_exp_clauses.erl:23: :elixir_exp_clauses.clause/5
(elixir) src/elixir_fn.erl:33: anonymous fn/3 in :elixir_fn.expand/3
(stdlib) lists.erl:1237: :lists.map/2
(elixir) src/elixir_fn.erl:36: :elixir_fn.expand/3

Here is my current progress:

defmacro anonymous_fn(parts) do
  quote bind_quoted: [parts: parts] do
    fn_branches = for {head, body} <- parts, do: {:->, [], [[head], body]}
    unquote({:fn, [], fn_branches})
  end
end

However, nested unquote fails with the same error unquote called outside quote.

At this point, I'm just going to use an anonymous function, the macro approach was redundant, but I would still be interested to know if this is possible.

Thanks in advance!

0
source share
1

, - , , .

, .:) , , ..

unquote , - , , unquote. , :

def foo do
  fn -> unquote(bar) end
end

, foo ? , , :

defmacro anonymous_fn(parts) do
  fn_branches = for {head, body} <- parts, do: {:->, [], [[head], body]}
  {:fn, [], fn_branches}
end

:

defmacro anonymous_fn(parts) do
  fn_branches = for {head, body} <- parts do
    quote do: (unquote(head) -> unquote(body))
  end
  {:fn, [], fn_branches}
end
+2

All Articles