snunezcr
Defining operations using protocols
I need to define a protocol for a scientific application based on quantities of various types. I want to use protocols since they abstract my code nicely. Is there a valid way to re-define math operators in protocols, e.g.
defprotocol PhysQuant do
@doc “Compute arithmetic operations”
def qa + qb
def qa - qb
def qa * qb
def qa / qb
def qa ^ qb
def exp(quantity)
def sin(quantity)
def cos(quantity)
def tan(quantity)
end
Thanks in advance.
Most Liked Responses
ityonemo
It’s possible. You can un-import from Kernel and re-import. For example:
https://github.com/ityonemo/annex/blob/experimental/test/experimental/elixir_tensor_test.exs
However, it’s somewhat discouraged.
wojtekmach
Agreed. Another approach is to limit operator overrides to a macro call so that outside of it things continue to work as usual. Here’s a proof-of-concept I did for Decimal [1] a while ago:
iex> require DecimalEval
iex> a = 1
iex> b = 2
iex> DecimalEval.eval (a + b) * "3.0"
#Decimal<9.0>
snunezcr
Thank you. The code in your link clarified many other questions I already had.








