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.
First Post!
dimitarvp
Please use triple backtick blocks to format code: Markdown cheat sheet.
And no, Erlang and Elixir do not allow overriding of operators per se. You are much better off using function names like add, sub, mul, div, mod etc.
Most Liked
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
Last Post!
ityonemo
just keep in mind that 1) the changes are lexically scoped. That’s a good thing ™ since it contains the statefulness of potentially confusing conventions and 2) the changes are strictly opt-in, you can’t enforce it globally (AFAIK) and 3) they’re not composable. If someone else has a library that does that you can’t use it in the same code block as yours.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










