F#管道转发可以表示为:
let (|>) x f = f x
Run Code Online (Sandbox Code Playgroud)
例如:
let SimpleFunction (a : typeA) (b : typeB) (c : typeC)=
printf "OK."
// No problem here.
SimpleFunction a b c
// Using pipe-forward
c |> SimpleFunction a b
// No problem here. Interpreted as the same as above.
Run Code Online (Sandbox Code Playgroud)
但是,根据文档,管道转发操作符是左关联的.
https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/
所以,我期待管道前进声明:
// Original Expression
c |> SimpleFunction a b
// to be equivalent to:
(c |> SimpleFunction) a b
// Which is equivalent to:
SimpleFunction c a b
// Error!! SimpleFunction takes typeA, then typeB, then typeC.
Run Code Online (Sandbox Code Playgroud)
为什么编译器不将管道转发表达式"解释"为错误表达式?我对运算符优先级/关联性有任何疑惑吗?
其他来源:
http://theburningmonk.com/2011/09/fsharp-pipe-forward-and-pipe-backward/
二元运算符的关联性仅在您有两个或更多相同运算符时才有意义.当你有不同的运算符(这里:|>和并置)时,重要的是它们的相对优先级.
|>因此,并置具有更高的优先级
c |> SimpleFunction a b
Run Code Online (Sandbox Code Playgroud)
被解析为
(c) |> (SimpleFunction a b)
Run Code Online (Sandbox Code Playgroud)
所以,根据定义|>,它等同于
(SimpleFunction a b) (c)
Run Code Online (Sandbox Code Playgroud)
这通常是写的
SimpleFunction a b c
Run Code Online (Sandbox Code Playgroud)
最后的等价是由于并置是左联合的.
|>左关联的事实意味着表达式像
x |> f |> g
Run Code Online (Sandbox Code Playgroud)
被解析为
(x |> f) |> g
Run Code Online (Sandbox Code Playgroud)
这相当于
g (f x)
Run Code Online (Sandbox Code Playgroud)
即|>表达函数组合链- 连续的管道步骤 - 而不是向函数传递更多参数.