我有以下函数,它只需要与n
2 的幂 ( 1, 2, 4, 8, 16, 32, 64, ...
)的幂值匹配:
defmodule MyModule do
def my_func(n) when is_power_of_two(n) do
## Some expression
end
def is_power_of_two(x) do
(x != 0)
and (x &&& (x - 1)) == 0)
end
end
首先,我尝试is_power_of_two
在模块中定义为一个函数,但它没有用,我收到了这个错误:
cannot invoke local is_power_of_two/1 inside guard
.
在此博客文章之后,我尝试将其定义为以下宏:
defmodule MyModule.Util do
defmacro is_power_of_two(x) do
quote do
(unquote(x) != 0)
and ((unquote(x) &&& (unquote(x) - 1)) == 0)
end
end
end
效果不佳,我收到以下错误:
cannot invoke local &&&/2 inside guard
似乎&&&
无法从when
宏扩展后的子句中调用按位运算符。
如何执行需要包含按位运算符的守卫的匹配?
错误消息具有误导性。你只是缺少一个import Bitwise
in MyModule.Util
。如果我添加import
:
defmodule MyModule.Util do
import Bitwise
defmacro is_power_of_two(x) do
quote do
(unquote(x) != 0) and ((unquote(x) &&& (unquote(x) - 1)) == 0)
end
end
end
defmodule MyModule do
import MyModule.Util
def my_func(n) when is_power_of_two(n) do
true
end
def my_func(_), do: false
end
IO.inspect MyModule.my_func(128)
IO.inspect MyModule.my_func(129)
输出:
true
false
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句