Fl4m3Ph03n1x
Zero-cost abstraction for NewTypes in Elixir
Background
Recently I have discovered this notion of “zero cost type wrappers”. Basically what this means is that you can create a new type by wrapping a primitive type (and the cost of doing this is low to non-existent). This new type would serve as an additional layer of abstraction and prevent certain categories of bugs at compile time.
For example, let’s assume we have this function (assume we have an Artist struct):
@spec new(artist :: String.t, country :: String.t, genre :: String.t) :: Artist.t
def new(n, c, g) do
%Artist{
name: n, country: c, genre: g
}
end
Now obviously I added the specs here for help. But you will notice that everything is String.t. This basically means I can incorrectly invoke this function:
MyModule.new("U.S.", "Metallica", "Heavy Metal") # name and country and swapped
The compiler would not complain.
NewType abstraction
To solve this issue, some people came up with this notion of wrapping primitive types into an abstraction. If you are from Scala you may know this as “Zero-cost abstraction for NewTypes”, if you are from Rust you may know it as the NewType Pattern and so on (this is a feature present in many languages these days).
scala code
opaque type Location = String
object Location{
def apply(value: String): Location = value
extension(a: Location) def name: String = a
}
This would create a new type called Location that wraps the String primitive type.
In Elixir, our function’s signature would now be:
@spec new(artist :: String.t, country :: Location.t, genre :: String.t) :: Artist.t
(you can also do the same for genre)
Elixir NewType wrappers?
Now, using the power of typespecs I could do something like:
@type location :: String.t()
And use it in my specs. But this would serve merely as documentation and would prevent no types of errors whatsoever.
The closest thing that comes to my mind, would be to define a struct:
defmodule Location do
defstruct [:name]
@type t :: %__MODULE__{name: String.t()}
@spec new(name :: String.t()) :: __MODULE__.t()
def new(name), do: %__MODULE__{name: name}
end
Ignoring the boilerplate code (we can just create a macro for that!) I think this is the closest I can get to having something like the NewType abstraction.
This would allow us to invoke the function like this:
MyModule.new("Metallica", Location.new("U.S."), Genre.new("Heavy Metal"))
We can’t swap parameters and have thus eliminated a category of errors. Further more, we did this at compile time.
Would it be zero-cost? I don’t think so, since I am replacing a String.t with a map that has 1 key. The overhead would probably be minimal, but I don’t think I could call it zero cost.
Questions
- How would you implement this abstraction in Elixir?
- Are there any optimizations one could do here?
- Is it possible to have a compile time check that prevents this category of errors using
typespecsonly? (I don’t think so, but please feel free to prove me wrong)
Most Liked
LostKobrakai
While I can see the usefulness of the general pattern one has to acknowledge that elixir is not a statically typed language. The compiler only has limited knowledge around the types of data at compile time (especially around everything message passing). So the remaining options are runtime checks.
As you noted things won’t be “zero cost” at runtime. The smallest way to add information to a piece of data would be a number per type or on the beam an atom, which at runtime is also basically a number. Erlang usually uses records for that {:user, "someone"}. Tuples afaik come with very little overhead in actual memory over just the two values itself (1). In elixir we usually don’t use tuples/records that much, we use maps/structs. Luckily small maps (<32 keys) are stored in (again afaik) a similar memory layout to tuples. Still a bit more overhead, but less than for large maps.
So those are the options to look at imo for deciding if the runtime hit is worthwhile. Generally I feel like structs are a good way to “type” data, but I wouldn’t do it for every scalar floating around in your system, but rather things which are reasonable entities or values in your system. E.g. Location in an event booking system makes sense. Wrapping every city string probably not.
tomekowal
I’d go with @aziz solution. I usually define the API for other modules to consume so it doesn’t hurt that much that the solution does not work in the same module. It works in other modules:
defmodule Title do
@opaque t :: binary
@spec new(binary) :: t()
def new(t), do: t
end
defmodule Artist do
@opaque t :: binary
@spec new(binary) :: t()
def new(a), do: a
end
defmodule Song do
@opaque t :: %{artist: Artist.t(), title: Title.t()}
@spec create(Artist.t, Title.t) :: t()
def create(artist, title), do: %{artist: artist, title: title}
end
defmodule Test do
alias Title
alias Artist
alias Song
def test() do
title = Title.new("Title")
artist = Artist.new("Artist")
# Wrong order of arguments causes Dialzyer error
Song.create(title, artist)
end
end
mix dialyzer produces
lib/zero_cost.ex:24:no_return
Function test/0 has no local return.
________________________________________________________________________________
lib/zero_cost.ex:29:call_without_opaque
Function call without opaqueness type mismatch.
Call does not have expected opaque terms in the 1st and 2nd position.
Song.create(_title :: Title.t(), _artist :: Artist.t())
________________________________________________________________________________
done (warnings were emitted)
Halting VM with exit status 2
Rafał Studnicki used this idea in one of his projects: https://www.youtube.com/watch?v=XGeK9q6yjsg He goes even further and with those types ![]()
However, there is some boilerplate involved and with dialyzer cryptic errors, I don’t see this solution getting too much traction ![]()
LostKobrakai
defmodule Location do
@type t :: {:location, String.t}
end
But yes you’d have to unwrap the value - just like with a struct. This is runtime data we’re dealing with. You cannot implicitly wrap a string to be tagged “a location” and the runtime would infer that tag from the plain string received. There’s things you can do in a statically typed language you simply cannot do if you don’t have a statically typed language.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








