2016-05-15 36 views
3

我无法理解为什么这个工程:药剂管无效语法

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 

为什么管操作使得这里的两种情况之间的区别?

回答

9

的空白改变的优先级是如何解决:

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())" 

而且药剂不支持保留功能和括号之间的空间 - 它只能由意外的一元函数,因为括号是可选的: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: '(' 
+0

oohhh,谢谢,完全没有想到会是这样:)非常好的解释! –