marick

marick

Macros that define functions: conversions between an atom and an AST leaf that is an atom

Sometimes an argument to a macro is to be used as the name of a function being created with def. That’s straightforward[*].

But suppose the name of the function is also to be used as an atom within the body of a function. (Think of using the name to look up a value in the application environment.) Is there a better way to do that than what I show below?


Example 1: config2 from_config2

The config2 macro is to define a zero-argument function from_config2 that returns :from_config2. The following implementation works:

  defmacro config2(quoted_name) do
    # quoted_name is this tuple: `{:from_config_2, [line: 75], nil}`
    name_atom = elem(quoted_name, 0)
    quote do
      def unquote(quoted_name), do: unquote(name_atom)
    end
  end

Plucking a value from a tuple (line 3) seems rather slimy. Is there a better way?

Example 2: config3 :from_config3

This is the same as the above, except that the macro argument is an explicit atom (and thus not wrapped in a tuple). So I can do the wrapping, as in line 3 below:

  defmacro config3(name_atom) do
    # name_atom is just `:from_config_3`
    quoted_name = {name_atom, [], nil}
    quote do
      def unquote(quoted_name), do: unquote(name_atom)
    end
  end

Is there a better way?


[*] If you haven’t done it before, defining a function in a macro looks something like this:

  defmacro defchain(head, do: body) do
    quote do
      def unquote(head) do
        _called_for_side_effect = unquote(body)
        unquote(value_arg(head))
      end
    end
  end

One note: guards make a function definition’s syntax tree a little weird. So if you want to write macros that handle this:

  defchain assert_field(kvs, list) when is_list(list) do
    assert_fields(kvs, list)
  end

… you might have to do some processing like this. That’s the definition of value_arg as used above.

Marked As Solved

kip

kip

ex_cldr Core Team

Given that you are looking to define a function call, and to also extract the atom that is the name of the function being called then pattern matching would be more idiomatic but not materially different to using Kernel.elem/2.

Given that that AST:

  • for :fun_name is :fun_name and
  • for fun_name() is {:fun_name, [], [])

Then

{fun_name_as_atom, _meta, _params} = {:fun_name, [], []) would seem to be the idiomatic way to go.

Using your example:

  defmacro config2(quoted_name) do
    # quoted_name is this tuple: `{:from_config_2, [line: 75], nil}`
    {name_atom, _meta, _args} = quoted_name
    quote do
      def unquote(quoted_name), do: unquote(name_atom)
    end
  end

Also Liked

lud

lud

Your examples are fine.

This may be shorter, but may not be better:

  defmacro config2({name, _, []}) do
    quote do
      def unquote(name)(), do: unquote(name)
    end
  end
lud

lud

No because in my snipped I wrote def unquote(name)() (with the parens for the call).

marick

marick

Wow! I would not have guessed that would work.

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement