xiang0x48
xiang0x48

Reputation: 651

chaining functions with multiple outputs in julia

Julia has good support for chaining functions using |> like

x |> foo |> goo

However for functions with multiple inputs and multiple outputs, this does not work:

julia> f(x, y) = (x+1, y+1)
julia> f(1, 2)
(2, 3)
julia> (1,2) |> f |> f
ERROR: MethodError: no method matching f(::Tuple{Int64,Int64})
Closest candidates are:
  f(::Any, ::Any) at REPL[3]:1
Stacktrace:
[1] |>(::Tuple{Int64,Int64}, ::typeof(f)) at ./operators.jl:813
[2] top-level scope at none:0

We can define f to accept tuple to make it work.

julia> g((x,y)) = (x+1, y+1)
julia> (1,2) |> g |> g
(3, 4)

But the definition of g is not as clear as f. In doc of julia, I've read that functions are calling on tuples, but actually there is differences.

Is there any elegant solution for this?

Upvotes: 3

Views: 392

Answers (2)

Steven Siew
Steven Siew

Reputation: 873

or you can use an Array

julia> f(x) = [x[1]+1,x[2]+1]
f (generic function with 1 method)

julia> [1,2] |> f |> f
2-element Array{Int64,1}:
 3
 4

Upvotes: 1

Gnimuc
Gnimuc

Reputation: 8566

you could also use splatting operator ... like this:

julia> f(x, y) = (x+1, y+1)
f (generic function with 1 method)

julia> (1,2) |> x->f(x...) |> x->f(x...)
(3, 4)

Upvotes: 4

Related Questions