Skip to content

Instantly share code, notes, and snippets.

@rpip
Last active December 10, 2015 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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