Skip to content

Instantly share code, notes, and snippets.

Created March 5, 2016 15:52
Show Gist options
  • Save anonymous/e28e811452240578ab24 to your computer and use it in GitHub Desktop.
Save anonymous/e28e811452240578ab24 to your computer and use it in GitHub Desktop.
defmodule MyFunc do
defmacro dynamic_fn(n) do
quote do
def unquote(:"multiply_#{n}")(arg) do
unquote(n) * arg
end
end
end
defmacro dynamic_fn2(n) do
quote bind_quoted: [n: n] do
def unquote(:"multiply_#{n}")(arg) do
unquote(n) * arg
end
end
end
defmacro dynamic_fn3(name) do
quote bind_quoted: [name: name] do
def unquote(name)(), do: unquote(name)
end
end
end
defmodule TestFunc do
require MyFunc
MyFunc.dynamic_fn(2) # works fine
#[6, 7] |> Enum.each(&MyFunc.dynamic_fn/1) # throws error
MyFunc.dynamic_fn2(4) # works fine
#[8, 9] |> Enum.each(&MyFunc.dynamic_fn2/1) # throws error
MyFunc.dynamic_fn3(:first_fn) # works fine
[:second_fn, :third_fn] |> Enum.each(&MyFunc.dynamic_fn3/1) # works fine
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment