vrod

vrod

First time Elixir macro -- generate similar functions?

This is my first time I am looking at macros. I think I understand they are something like “pre generation” of code. Maybe something like using PHP templates to make Javascript code – they make Elixir code before it runs? OK this is maybe a bad example.

What I am trying to do is this: I have multiple functions that are almost all the same. Each one gets a thing from an API. Each one is the same, but each one returns a different struct. All of them look like this:

defmodule Thing1Resolver do
   def get_one(args) do
     data = get_from_api(args)
     struct(Thing1, args)
   end
end

The only difference is the module Thing1 is different for each function (Thing2, Thing3, Thing4). Can I write a macro to use and build functions like this? So maybe my resolver modules look like

defmodule Thing1Resolver do
    use Shared, struct: Thing1
end

Is this possible? Maybe it is a bad idea. I want to understand how it works and then I can decide.

Thankyou

Most Liked

al2o3cr

al2o3cr

You could use macros for this, but since it’s really just substituting a value for thing it’s not a great fit.

Macros are really powerful when you want a piece of code to generate multiple related functions / data, or code that depends on the whole module’s settings. For instance, the Ecto.Schema.schema macro generates __changeset__ and __schema__ functions after all the schema fields are defined along with setting many module attributes.

al2o3cr

al2o3cr

Because this:

defmodule FooBar.Thing1Resolver do
  use FooBar.Share, struct: FooBar.Thing1
  import FooBar.Creator

  defcreate(FooBar.Thing1)
end

is harder to read than this:

defmodule FooBar.Thing1Resolver do
   def new(args) do
    struct(FooBar.Thing1), args)
  end

  def create(args) do
    struct(FooBar.Thing1), args)
  end
end

For instance, it’s considerably less obvious the functions generated in Thing1Resolver in the first version are identical since their definitions are split among two modules and use arguments differently.

Another approach to consider: put as little code in the macro as possible and call out to the real implementation. This is part of what happens when you say use Ecto.Repo in your application:

defmodule FooBar.Share do
  defmacro __using__(opts) do
    struct_name = opts[:struct]

    quote do
      def new(args) do
        FooBar.Share.new(unquote(struct_name), args)
      end
    end
  end

  def new(struct_name, args) do
    struct(struct_name, args)
  end
end

defmodule Wat do
  use FooBar.Share, struct: Wat

  defstruct [:val]
end

Wat.new(val: 1)

Here the macro generates a function which adds in the argument passed to use but delegates all the functionality to a function defined on FooBar.Share. There’s a tiny compilation space/performance improvement since less AST is generated, and there’s less thinking about tricky things with unquote.

John-Goff

John-Goff

Why not just have a function that takes the type of struct? Something like

def get_generic(thing, args) do
  data = get_from_api(args)
  struct(thing, args)
end

Also note with this code you’re not using the API result for anything, and it’s essentially doing nothing, assuming there are no side effects from that API call.

kokolegorille

kokolegorille

You could adapt something like…

defmodule Demo do
  for x <- [1, 2, 3] do
    def unquote(String.to_atom("get_#{x}"))(), do: unquote(x)
  end
end

# then

iex> Demo.get_1
1
iex> Demo.get_2
2
iex> Demo.get_3
3

But it won’t work because You will have functions with same signature… You need to do a little bit more work, like pattern match in functions arguments.

BTW Your code won’t work for multiple reasons…

defmodule Thing1Resolver do
  # There is no way to distinguish signature
   def get_one(args) do
     # You define data, but don't use it
     # get_from_api => side effect!
     data = get_from_api(args)
     # I suppose args should be data
     struct(Thing1, args)
   end

  # As You see, distinction is only inside the function body.
  def get_one(args) do
    struct(Thing2, args)
  end
end

How to solve this? You could call get_from_api outside the function, and pass data as argument.

You could solve with…

defmodule Thing1Resolver do
  def get_one(thing, data), do: struct(thing, data)
end

# and call

data = get_from_api(args)
Thing1Resolver.get_one(any, data)

But if You look at this, well, get_one is just the same as calling struct :slight_smile:

Marcus

Marcus

In theory you can do it that way, but it is not the right way. Or I don’t understand you right. Here is an example how things can work. Please note that this example is not good under several aspects.

defmodule FooBar.Thing1 do
  defstruct [val: nil, type: This.Is.Thing1]
end

defmodule FooBar.Thing2 do
  defstruct [val: nil, type: This.Is.Thing2]
end

defmodule FooBar.Share do
  defmacro __using__(opts) do

    quote do
      def new(args) do
        struct(unquote(opts[:struct]), args)
      end
    end
  end
end

defmodule FooBar.Creator do
  defmacro defcreate(thing) do
    quote do
      def create(args) do
        struct(unquote(thing), args)
      end
    end
  end
end

defmodule FooBar.Thing1Resolver do
  use FooBar.Share, struct: FooBar.Thing1
  import FooBar.Creator

  defcreate(FooBar.Thing1)
end

defmodule FooBar.Thing2Resolver do
  use FooBar.Share, struct: FooBar.Thing2
  import FooBar.Creator

  defcreate(FooBar.Thing2)
end

That can be used like:

iex(1)> FooBar.Thing1Resolver.new(val: 55)
%FooBar.Thing1{type: This.Is.Thing1, val: 55}
iex(2)> FooBar.Thing2Resolver.new(val: 44)
%FooBar.Thing2{type: This.Is.Thing2, val: 44}
iex(3)> FooBar.Thing1Resolver.create(val: 55)
%FooBar.Thing1{type: This.Is.Thing1, val: 55}
iex(4)> FooBar.Thing2Resolver.create(val: 55)
%FooBar.Thing2{type: This.Is.Thing2, val: 55}

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
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
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement