Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Macro: Power ** function

Tags:

macros

elixir

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?

like image 443
mgwidmann Avatar asked May 02 '15 21:05

mgwidmann


2 Answers

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
like image 146
whatyouhide Avatar answered Oct 22 '22 23:10

whatyouhide


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.

like image 3
Patrick Oscity Avatar answered Oct 23 '22 01:10

Patrick Oscity