Fl4m3Ph03n1x

Fl4m3Ph03n1x

How to define Macro for a new Type?

Background

So, I am playing around with a concept named “NewType” and I am taking inspiration from languages like F# and Scala.

My objective, for learning purposes mostly, is to build a macro that makes creating this abstraction something that takes no more than a single line of code.

Intended usage

I would like to create a macro that allows me to do something like this:

defmodule User do
  require NewType # an absolutely original name for the macro :D

  deftype Name, String.t() # Usage of said macro. Here I am defining a new type called "Name"

  @enforce_keys [:name, :age]
  defstruct [:name, :age]
  @type t :: %__MODULE__{
          name: Name.t,
          age: integer()
        }

  @spec new(Name.t, integer) :: User.t
  def new(name, age), do: %User{name: name, age, age}  
end

And now, here is how I could create a User:

defmodule Test do
  alias User
  import User.Name

  @spec run :: User.t
  def run do
    name = Name("John")
    User.new(name, 25)
  end
end

How to implement this interface?

This interface might remind you a little of the Record interface. That’s because I think its API has some good ideas I would like to explore.

So, as a starting point I tried reading the source code for Record, but I was not really able to pick it up and use it to create an implementation for my use case, mainly because I don’t need/want to interface with Erlang records at all.

So, an implementation possibility would be to, under the hood, turn this into a tuple:

defmodule NewType do
  defmacro new(name, val) do
    quote do
      NewType.to_tuple(unquote(name), unquote(val))
    end
  end

  def to_tuple(name, val), do: {String.to_atom(name), val}
end

However, this is miles away from the interface I want to create …

Questions

  1. Using Elixir macros, is it possible to create the API I am aiming for?
  2. How can I change my code to achieve something like Name("John")?

Marked As Solved

Fl4m3Ph03n1x

Fl4m3Ph03n1x

My Answer

After reading more about macros in Elixir, talking to the community and reading about NewType, I have refined my ideas. While the exact implementation of my original idea is not possible, with some changes you can still get the core benefit of NewType.

Changes to original idea

  • No usage of Name("John") syntax. As explained in this post this syntax is not valid in Elixir.
  • No defguard. Because the type is @opaque it is not possible to have a guard that analyses the internal structure of the data without having dialyzer complaining. Since the main goal here is to have Dialyzer help me detect issues, and since the internal structure of the opaque data can only be analyzed by functions that belong to the module itself, this means this idea is not possible.
  • No verification on data type when invoking new. Originally I thought about having some verification mechanism, but this is not necessary, since dialyzer will let the user know if the user is invoking new with an incorrect parameter.
  • No self-generated functions. Instead of having Age.age? or Name.name? I have opted for the more general NewType.is_type?/2, which will accomplish the same and is more general.

Code

With these changes in mind, this is the macro I came up with:

defmodule NewType do
  defmacro deftype(name, type) do
    quote do
      defmodule unquote(name) do
        @opaque t :: {unquote(name), unquote(type)}

        @spec new(value :: unquote(type)) :: t
        def new(value), do: {unquote(name), value}

        @spec extract(new_type :: t) :: unquote(type)
        def extract({unquote(name), value}), do: value
      end
    end
  end

  @spec is_type?(data :: {atom, any}, new_type :: atom) :: boolean
  def is_type?({type, _data}, new_type) when type == new_type, do: true
  def is_type?(_data, _new_type), do: false
end

Which can be used like:

type.ex:

defmodule Type do
  import NewType

  deftype Name, String.t()
end

test.ex:

defmodule Test do
  alias Type.Name

  @spec print(Name.t()) :: binary
  def print(name), do: Name.extract(name)

  def run do
    arg = 1
    name = Name.new(arg) # dialyzer detects error !
    {:ok, name}
  end
end

Popular Backend topics Top

New
PragmaticBookshelf
It's easier to learn how to program a computer than it has ever been before. Now everyone can learn to write programs for themselves—no p...
New
ariandanim
Hello, i am facing difficult using webpack when to install within phoenix framework 1.5.7 because the webpack is still version 4.x.x inf...
New
CinderellaMan
Create a cryptocurrency trading bot in Elixir (YouTube videos, ebook pay what you want) <span class="hashtag-icon-placeholder"></span>eli...
New
joshi
Hey everybody! I’m working on the project that includes import of Oracle data to PostgreSQL. That data comes as Oracle export (expdp) fi...
New
First poster: bot
A new Rust blog post/announcement has been posted! Get the full details here: Announcing Rust 1.53.0 | Rust Blog
New
PragmaticBookshelf
Learn Functional Programming by building a complete web application that uses Kotlin, TDD with end-to-end tests, and CQRS and Event Sourc...
New
PragmaticBookshelf
Programming Ruby is the most complete book on Ruby, covering both the language itself and the standard library as well as commonly used t...
New
ManningBooks
Dodge the common mistakes that even senior developers make, take full advantage of static analysis tools, and deliver robust and error-fr...
New
PragmaticBookshelf
Leverage Elixir and the Nx ecosystem to build intelligent applications that solve real-world problems in computer vision, natural languag...
New

Other popular topics Top

wolf4earth
@AstonJ prompted me to open this topic after I mentioned in the lockdown thread how I started to do a lot more for my fitness. https://f...
New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
There’s a whole world of custom keycaps out there that I didn’t know existed! Check out all of our Keycaps threads here: https://forum....
New
PragmaticBookshelf
“Finding the Boundaries” Hero’s Journey with Noel Rappin @noelrappin Even when you’re ultimately right about what the future ho...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
rustkas
Intensively researching Erlang books and additional resources on it, I have found that the topic of using Regular Expressions is either c...
New
foxtrottwist
A few weeks ago I started using Warp a terminal written in rust. Though in it’s current state of development there are a few caveats (tab...
New
PragmaticBookshelf
Author Spotlight: Karl Stolley @karlstolley Logic! Rhetoric! Prag! Wow, what a combination. In this spotlight, we sit down with Karl ...
New
DevotionGeo
I have always used antique keyboards like Cherry MX 1800 or Cherry MX 8100 and almost always have modified the switches in some way, like...
New