Elixir管道无效语法



我很难理解为什么这样做:

1..1000 |> Stream.map(&(3 * &1)) |> Enum.sum

虽然这不是:

1..1000 |> Stream.map (&(3 * &1)) |> Enum.sum

唯一的区别是.map之后的空间据我所知,在这种情况下,长生不老药不应该关心空白。

iex中运行上述代码会产生以下错误:

warning: you are piping into a function call without parentheses, which may be ambiguous. Please wrap the function you are piping into in parentheses. For example:
foo 1 |> bar 2 |> baz 3
Should be written as:
** (FunctionClauseError) no function clause matching in Enumerable.Function.reduce/3
foo(1) |> bar(2) |> baz(3)
(elixir) lib/enum.ex:2776: Enumerable.Function.reduce(#Function<6.54118792/1 in :erl_eval.expr/5>, {:cont, 0}, #Function<44.12486327/2 in Enum.reduce/3>)
(elixir) lib/enum.ex:1486: Enum.reduce/3

为什么管道操作员在这里区分这两种情况?

空格改变优先级的解析方式:

iex(4)> quote(do: Stream.map(1) |> Enum.sum) |> Macro.to_string 
"Stream.map(1) |> Enum.sum()"
iex(5)> quote(do: Stream.map (1) |> Enum.sum) |> Macro.to_string
"Stream.map(1 |> Enum.sum())"

此外,Elixir不支持在函数和圆括号之间留空格——它只是意外地适用于一元函数,因为圆括号是可选的:foo (1)foo((1))相同。您可以看到,具有更多参数的函数不支持它:

iex(2)> quote(do: foo (4, 5))
** (SyntaxError) iex:2: unexpected parentheses. 
If you are making a function call, do not insert spaces between
the function name and the opening parentheses. 
Syntax error before: '('

最新更新