简体   繁体   中英

Elixir Macro: Power ** function

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 (eg, <~> ), 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM