2015-08-28 37 views
2

我想使用的元組與管道運營商,|>一個匿名函數一起像如何在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 

顯然,(1,2)元組沒有得到映射到(x,y)

的努力之後我有點意識到,我可以通過

(1,2) |> x -> x[1]^2 + x[2]^2

規避這個問題,但後者不是因爲在某些情況下,第一種方式一樣優雅。如果我想在第一個F#方法中將(1,2)映射到(x,y),語法應該是什麼樣子?

+0

這是一個[相關Google-Groups討論](https://groups.google.com/forum/#!topic/julia-dev/q_mPbNwVXi0)。 – Jubobs

回答

1

您可以定義泛型函數|>,它利用參數的元組,並將其映射到函數的形式參數,像這樣的新方法:

julia> Base.|>(xs::Tuple, f) = f(xs...) 
|> (generic function with 7 methods) 

julia> let 
      x = 1 
      y = 2 

      # just messing around... 
      (x, y) |> (x, y) -> (2x, 5y) |> 
        divrem    |> 
        complex   |> 
        x -> (x.re, x.im) |> 
        divrem    |> 
        (x...) -> [x...] |> 
        sum    |> 
        float 

     end 
0.0 
3

無需流水線,你會使用圖示運營商在這種情況下

((x,y) -> x^2 + y^2)((1,2)...) 

隨着流水線

julia> (1,2)... |> (x,y) -> x^2 + y^2 
ERROR: MethodError: `|>` has no method matching |>(::Int32, ::Int32, ::Function) 

所以,你可以擴展|>處理兩個參數

import Base.|> 
|>(x,y,f) = f(x,y) 

julia> (1,2)... |> (x,y) -> x^2 + y^2 
5 
相關問題