简体   繁体   English

Elixir Macro:Power **功能

[英]Elixir Macro: Power ** function

Looking through the Elixir source I see that multiplication is defined like this: 查看Elixir的源代码,我看到乘法定义如下:

@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 **. 我尝试使用unquote将其变成宏,使用:“ **”而不是**。 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 * ). 二进制运算符是在Elixir中预定义的,这意味着Elixir解析器将仅解析一堆运算符(显然包括* )。 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. 有一些“免费”运算符,即Elixir能够解析但语言本身未使用的运算符(例如<~> ),但是**不在其中。

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. Elixir没有**运算符。 You cannot define a new infix operator without changing and recompiling at least the Elixir parser and the Macro module . 您必须至少更改和重新编译Elixir解析器Macro模块才能定义新的infix运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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