bibekp

bibekp

I am trying to refactor a module to incorporate protocols while still leaving part of the base module while handling polymorphism but am having some questions/challenges..

I have a module that handles a Strategy, it has some basic methods like new, setup, update. It also has a method called optimal that should be polymorphic.

Function optimal depends on the type of strategy. Right now the module implements one particular type of Strategy, let’s call this DominantStrategy. But eventually, I want to create another called MixedStrategy. I would like to reuse the base Strategy methods new, setup, update, while specifying the individual strategy’s implementation of optimal separately.

defmodule Strategy do
  defstruct ...

  def new(args) do ... end
  def setup(%Strategy{} = s, data) do ... end
  def update(%Strategy{} = s, data) do ... end
  def optimal(%Strategy{} =s) do ... end
end

Let’s say I were to create a protocol called Decision which declares optimal

defprotocol Decision do
  def optimal() 
end

Then I would create the code implementing the protocol like so:

defmodule DominantStrategy do
  defstruct ...
  def optimal(%DominantStrategy{} = strategy) do
    ...
  end

  defimpl Decision, for: DominantStrategy do
    def optimal(%DominantStrategy{} = strategy) do
     DominantStrategy.optimal(strategy)
    end
end

defmodule MixedStrategy do
  defstruct ...
  def optimal(%MixedStrategy{} = strategy) do
    ...
  end
  defimpl Decision, for: MixedStrategy do
    def optimal(%MixedStrategy{} = strategy) do
     MixedStrategy.optimal(strategy)
    end
end

So my question is: how do I make this work with the Strategy module if the DominantStrategy and MixedStrategy structs are the same as the Strategy struct? Is there a more FP way to handle this?

Specifically:

  • Do I eliminate the Strategy struct and hence the %Strategy{} = s pattern match? 
    
  • Do I operate on the DominantStrategy struct and MixedStrategy struct generically in my top level methods like setup/update?
    
  • Does Strategy.new now return the specific Strategy implementation struct?
    
  • How to ensure the different structs (DominantStrategy, MixedStrategy) adhere to a common structure?
    

    defmodule Strategy do
    def new(args) do
    case args.type do
    :mixed → MixedStrategy.new(args)
    :dominant → DominantStrategy.new(args)
    _ → raise “Error”
    end

    def setup(s, data) do ... end
    def update(s, data) do ... end
    def optimal(s) do Decision.optimal(s) end
    

    end

Apologies in advance if this question type has been previously asked. A link would be appreciated.

If not, I would appreciate suggestions on the best way to go about this

PS. The presentation Well-Typed Elixir briefly touches on this.

– Thank you
Bibek

Showing Posts 1 to 3

bbense

bbense

It really sounds like you want a behaviour, not a protocol.

Protocols are for calling the same function on different data types.

Behaviours are for a custom implementation of a function for each module. In essence a behaviour is a promise that your module implements a function of name X with arity Y. So that if I pass in
the module name to another module it can use

Kernel.apply(module, :optimal, [strategy])

bbense

bbense

In the case of Structs, they are really just Maps with a special key that identifies the module that they are associated with.

iex> foo = 1..3
iex> bar = Map.get(foo, :“__struct__”)
iex> Kernel.apply(bar, :“range?”, [foo]) == Range.range?(foo)

bibekp

bibekp OP

Thanks there @bbense.

I guess more than passing around different types I am more passing around modules – hence the use of behaviors.

This older post helps to distinguish between the different types of polymorphic activity

My only minimal requirement would be for another module to abstract away the custom behaviors so my client code doesn’t need to worry about DominantStrategy vs. MixedStrategy

— All posts loaded —

Where Next? Top

Trending in Questions Top

Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
mandar1045
I load tested a plain Phoenix chat app backed by Postgres with 100 million messages in it, everything on default settings, to see what br...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
261 13183 112
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
charlenopires
Hi everyone :waving_hand: I’ve been working on PhiaUI, an open-source UI component library for Phoenix LiveView, and I wanted to share i...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews