Skip to content

Instantly share code, notes, and snippets.

@rpip
Last active August 13, 2024 10:50
Show Gist options
  • Save rpip/f9952c19c533dc6fb4b3 to your computer and use it in GitHub Desktop.
Save rpip/f9952c19c533dc6fb4b3 to your computer and use it in GitHub Desktop.
Arithmetic protocol for Elixir
defprotocol Arithmetic.Add do
@moduledoc """
The Arithmetic.Add protocol is responsible for adding items.
The only function required to be implemented is
`__add__` which does the addition.
"""
def __add__(left, right)
end
defimpl Arithmetic.Add, for: Decimal do
alias Decimal, as: D
def __add__(left, right) when is_decimal(right) do
D.add(left, right)
end
def __add__(left, right) do
D.add(left, D.new(right))
end
end
defimpl Arithmetic.Add, for: Integer do
def __add__(left, right) do
:erlang.+(left, right)
end
end
defimpl Arithmetic.Add, for: Float do
def __add__(left, right) do
:erlang.+(left, right)
end
end
## In Kernel.ex, line 822
@spec (number + number) :: number
def left + right do
Arithmetic.Add.__add__(left, right)
end
## Arithmetic.Add in action
alias Decimal, as: D
d1 = D.new(23.6)
d2 = D.new(9.54)
d1 + d2 # ==> Arithmetic.Add.__add__(d1, d2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment