【发布时间】:2018-01-01 10:57:18
【问题描述】:
为了更好地理解 Elixir 语言,我想尝试通过添加独占范围运算符 ... 来进行运算符重载。一个例子:1...10 然后将创建一个从 1 到但不包括 10 的范围。 (例如1...10 == 1..9)
所以,我查找了the definition of ..,因为... 的功能当然会非常相似。
Mmy 模块然后变成:
defmodule Sequences.Ranges do
defmacro first ... last do
case is_float(first) or is_float(last) or
is_atom(first) or is_atom(last) or
is_binary(first) or is_binary(last) or
is_list(first) or is_list(last) do
true ->
raise ArgumentError,
"ranges (first...last) expect both sides to be integers, " <>
"got: #{Macro.to_string({:"Sequences.Ranges...", [], [first, last]})}"
false ->
case __CALLER__.context do
nil -> quote do: Elixir.Range.new(unquote(first), unquote(last-1))
_ -> {:%{}, [], [__struct__: Elixir.Range, first: first, last: (last-1)]}
end
end
end
end
但是,在编译此模块时,我收到以下错误:
== Compilation error on file lib/sequences/ranges.ex ==
** (CompileError) lib/sequences/ranges.ex:6: cannot invoke local .../1 inside match
(stdlib) lists.erl:1353: :lists.mapfoldl/3
我做错了什么?
【问题讨论】:
标签: macros operator-overloading elixir