Fer*_*enc 2 tuples pipe anonymous-function julia
我正在尝试将元组与管道运算符|>一起使用,以及一个匿名函数,如
(1,2) |> (x,y) -> x^2 + y^2
但收到错误消息:
wrong number of arguments
while loading In[59], in expression starting on line 1
in anonymous at In[59]:1
in |> at operators.jl:178
Run Code Online (Sandbox Code Playgroud)
显然,(1,2)元组没有映射到(x,y).
经过一些尝试后,我意识到我可以通过以下方式规避问题
(1,2) |> x -> x[1]^2 + x[2]^2
但在某些情况下,后者不如第一种方式优雅。如果我想以第一种方式映射(1,2)到(x,y),语法应该是什么样的F#?
如果没有流水线,您将在这种情况下使用 splat 运算符
((x,y) -> x^2 + y^2)((1,2)...)
Run Code Online (Sandbox Code Playgroud)
带流水线
julia> (1,2)... |> (x,y) -> x^2 + y^2
ERROR: MethodError: `|>` has no method matching |>(::Int32, ::Int32, ::Function)
Run Code Online (Sandbox Code Playgroud)
所以你可以扩展 |> 来处理两个参数
import Base.|>
|>(x,y,f) = f(x,y)
Run Code Online (Sandbox Code Playgroud)
瞧
julia> (1,2)... |> (x,y) -> x^2 + y^2
5
Run Code Online (Sandbox Code Playgroud)