denna

denna

Combining Protocol and Behaviour - how to call a a function on a Module that inherits the function from another Module?

I am trying to provide a way to create something like inheritance.
i want to be able to call a a function on a Module that inherits the function from another Module. Is the following the most straightforward way?

defprotocol Proto do
  @spec foo(t()) :: charlist()
  def foo(item)
end

defmodule SpecializedProto do
  @callback info() ::  charlist()
end

defimpl Proto, for: Atom do
  @impl true
  def foo(item) do
    apply(item,:foo,[item])
  end
end

defimpl Proto, for: SpecializedProto do
  @impl true
  def foo(item) do
    apply(item,:info,[])
  end
end

defmodule Test do
  @behaviour SpecializedProto
  def info(), do: "test"
  defdelegate foo(x), to: Proto.SpecializedProto
end

Proto.foo(Test)

Most Liked

al2o3cr

al2o3cr

This isn’t what protocols are for, and probably (I have not run it) doesn’t work like you really want.

For the above declaration to make sense, you’d need to be calling Proto.foo with a %SpecializedProto{} struct.

Protocols solve a particular problem: how to make a function handle many data types that aren’t known by the function’s original authors. A simple example from the stdlib is String.Chars, which defines to_string and is used by the kernel to_string function.

Without protocols, the only way to write String.Chars.to_string would be with many heads:

defmodule String.Chars 
  # non-protocol version
  def to_string(v) when is_integer(v), do: ...
  def to_string(v) when is_map(v), do: ...
  def to_string(v) when is_list(v), do: ...
  # etc
end

However, having custom formatting for user-defined structs would require adding new clauses to String.Chars.to_string which isn’t supported (or particularly practical).

Protocols let you do that kind of dispatching because defimpls don’t have to be supplied all-at-once like defs.


A general suggestion when prototyping something like this: start out by writing a straightforward implementation that does what you want and uses the components you’re creating. Copy-paste code FREELY during this initial part, but try to keep changes to copied code clearly labeled.

Once you’ve got things sketched out enough, only then start thinking about how to DRY things out / reduce boilerplate / do macro-fu / etc. It will be a lot more obvious where you need flexibility like protocols with working code.

Last Post!

al2o3cr

al2o3cr

Your example is more readable if some of the reuse of the name SpecializedProto is removed (here are the changed clauses):

defimpl Proto, for: UnimportantName do
  @impl true
  def foo(item) do
    SpecializedProto.info(item)
  end
end

defimpl Proto, for: Test  do
  defdelegate foo(x), to: Proto.UnimportantName
end

I’m still not understanding the intent of passing an atom versus a struct in these functions, but I suspect that’s because that argument never gets used.

For instance, think about the path that a call like SpecializedProto.info(Test) takes:

  • dispatched to the Atom implementation, calls Test.info(Test)
  • Test.info(Test) delegates to SpecializedProto.Test.info(Test)
  • the SpecializedProto implementation for Test structs then receives the atom Test instead of a struct

Perhaps something like this would be better:

defimpl SpecializedProto, for: Atom do
  @impl true
  def info(item) do
    apply(item,:info,[struct(item)])
  end
end

Then you don’t need the defdelegate info(...) on Test, and SpecializedProto.Test always gets the struct that it expects.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement