JKWA

JKWA

Author of Advanced Functional Programming with Elixir

Polymorphism in Elixir

I didn’t have room for this in my book, Advanced Functional Programming with Elixir , but I still thought it was worth sharing on my blog.

Most Liked

JKWA

JKWA

Author of Advanced Functional Programming with Elixir

I admit, I’m having a bit of trouble giving helpful advice on this one.

Your goal, as I understand it, is to reduce Ecto boilerplate, and you’re also, in a sense, extending Ecto’s macro system. Within your project, I don’t see a problem, except that it introduces a bit of indirection that you’ll need to make sure your colleagues understand.

From the perspective of protocols, what hung me up is that I was looking for the polymorphism problem you were solving, but in the end, I think you’re using the protocol more as a contract.

Is this generalizable? I see some tight coupling to your domain, so my answer would be probably not, but I might be misunderstanding.

Is there another way to solve it? Sure. But you’re approaching it from a Ruby context, and I don’t have enough Ruby experience to say whether there’s a better alternative through that lens.

christhekeele

christhekeele

I would say protocols are for datatype polymorphism, often to get similar behaviour from different input data. Behaviours are for functional polymorphism, often to get different implementation details from similar contracts. Both can solve similar problems but have their own idiomatic wood grains to cut with or against.

Both involve functions accepting dynamic input that changes how the program executes: just as a function that accepts dynamic data may invoke a protocol to get different results, a function that accepts a dynamic module may invoke a behaviour to get different results.

Generally, unless we are doing supervision stuff/adapter work, our applications want to act similarly on different data more than we want them to act differently on similar interfaces, which is more of a library concern. Additionally, the type system and dialyzer work well enough with dynamic data types but dynamic modules is currently more of a black box for editor experiences. So I’d say the average application has more reason to be concerned with protocols than behaviours in practice, despite both mechanisms being open for extension in some sense to application developers.

But I would disagree with the claim that behaviours are not a mechanism for polymorphism; just a mechanism with different and less-common aims. I think my first paragraph there is a half-remembered direct quote from José, I’ll see if I can find the source. Some keynote maybe?

JKWA

JKWA

Author of Advanced Functional Programming with Elixir

We’re probably just interpreting the term “polymorphism” a bit differently. I’m using the Strachey definition, where the runtime selects behavior based on the type of the input. Under that (admittedly narrow) lens, behaviours don’t quite fit, since the caller selects the module explicitly. But in the end, it’s probably just semantics.

adamu

adamu

I didn’t have room for this in my book

This topic is explored in more depth in my book

These two statements contradict each other, perhaps the footer on the blog is generic and doesn’t apply in this case?

I think behaviours also deserve a mention along with protocols. My experience is that it’s quite rare to write a protocol, compared to a behaviour.

For example, Eq could also be implemented using a behaviour:

defmodule Eq do
  @callback eq?(a :: struct, b :: map) :: boolean

  def eq?(%type{} = a, b) do
    type.eq?(a, b)
  end
end

defmodule Cat do
  defstruct [:name, :microchip]

  @behaviour Eq

  def eq?(%Cat{microchip: a}, %{microchip: b}), do: a == b
end
iex(1)> Eq.eq?(%Cat{microchip: "foo"}, %{microchip: "foo"})
true
iex(2)> Eq.eq?(%Cat{microchip: "foo"}, %{microchip: "bar"})
false
JKWA

JKWA

Author of Advanced Functional Programming with Elixir

Yes, we’re both solving the same problem: defining a default comparison for a type.

Here’s how I might implement the homogeneous sort:


def sort(list, ord \\ Funx.Ord) when is_list(list) do

Enum.sort(list, Ord.Utils.comparator(ord))

end

This lets the caller sort a list using the domain’s default ordering or pass in a different Ord when needed. It supports cases where the same type needs multiple comparison strategies. It also allows Ord composition, making it easy to build more complex ordering logic.

Where Next?

Popular in Blog Posts Top

luckywatcher
Hey all! I just started a blog focused on web development in Elixir. I wrote my first article and thought I’d post it here for the whole...
New
sheharyarn
In this article, I talk about the Elixir library Delta we at Slab just open-sourced, its various features including support for Operation...
New
jordiee
https://medium.com/@jpiepkow/distributed-state-is-hard-5a0d384c2f3c
New
paulanthonywilson
https://furlough.merecomplexities.com/elixir/otp/tdd/2021/03/18/test-driving-otp-creating-a-registry-with-expiring-entries.html Followin...
New
paulanthonywilson
All a bit meta, but this is a quick post on creating a Jekyll blog post from a Livebook page. Posted via Devtalk (see this thread for ...
New
New
brainlid
Elixir has a built-in Zip library that comes with OTP. This post explores how to use the zip module and asks the important question: “Is ...
New
zachdaniel
In this post I explore the silos that exist in the Elixir ecosystem, the pros and cons, and what we can improve.
New
DevotionGeo
There are 3 main formatters for Erlang which you can use from the command-line, rebar3_format, Steamroller elmfmt. Visual Studio Cod...
New
mssantosdev
Our take on how to build a frontend style guide with Phoenix Components, Atomic Design and plain CSS, with focus on reusability and code ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement