Looking through the Elixir source I see that multiplication is defined like this:
@spec (number * number) :: number
def left * right do
:erlang.*(left, right)
end
I wanted to make a ** function to do power as an exercise. However, when I try, I get an exception and I can't figure out how to do it correctly.
@spec (number ** number) :: number
def left ** right do
:math.pow(left, right)
end
Always throws an error like:
** (SyntaxError) iex:7: syntax error before: '*'
I tried making it a macro, using unquote, using :"**" instead of **. Not sure why this doesn't work...
Any ideas?
Binary operators are predefined in Elixir, meaning that the Elixir parser will only parse a bunch of operators (which, obviously, include *
). You can see the list of operators roughly in this section of the parser. There are some "free" operators, that is, operators that Elixir is able to parse but that are not used by the language itself (e.g., <~>
), but **
is not among them.
Just to show that parseable operators can do what you want:
defmodule MyWeirdOperators do
def left <~> right do
:math.pow(left, right)
end
end
import MyWeirdOperators
3 <~> 4
#=> 81.0
Elixir does not have a **
operator. You cannot define a new infix operator without changing and recompiling at least the Elixir parser and the Macro
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With