How to define Macro for a new Type?

Sorry to comment on the previous idea – but that’s way too global. In a moderately big project you can have 5 different kinds of names. So to implement this properly you’d likely have to scope this somehow e.g. with module names (which are also atoms as you know):

defmodule MyApp.Types.Address.Name do
  def name?({__MODULE__, val}) when is_binary(val), do: true

In many languages, internally types get all sorts of fancy prefixes. That’s important. You don’t want only one Name to be ever allowed in your project.

Elixir offers an even neater way of doing this:

def is_type?({type, _data}, type), do: true # note the repeated `type` variable
def is_type?(_data, _new_type), do: false

Examples:

is_type?({:x, "something"}, :x} # returns true
is_type?({:x, "something"}, :y} # returns false

3 Likes