Chain.jl
Chain.jl copied to clipboard
Equivalent of `.|>` for array of functions
With the .|>
operator, I can apply arrays of functions to arrays of values
I’m new to julia but I guess that it is possible because it uses broadcast
?
functions = [(a -> a +1), (a -> a + 2)]
values = [0, 0]
r1 = values .|> functions
functions = [(a -> a +1) (a -> a + 2); (a -> a +3) (a -> a + 4)]
values = [0 0; 0 0]
r1 = values .|> functions
Is it possible to do the same with chain.jl ? I tried the @.
syntax but it doesn’t work.
Just started playing around with this package, so probably not the best guy to answer but:
Generally you can use the .|>
by directly calling the broadcast function with .
e.g.
julia> f(x) = x + 1
julia> @chain [1,2,3] f.()
3-element Vector{Int64}:
2
3
4
But what you are asking is really mapping one argument to one function, and that wouldn't work in your case. You can work around that with something a little bit more verbose like:
julia> functions = [(a -> a +1) (a -> a + 2); (a -> a +3) (a -> a + 4)]
julia> values = [0 0; 0 0]
julia> @chain values map.(functions, _)
2×2 Matrix{Int64}:
1 2
3 4
But as mentioned above, Idk if something more explicit can be done to broadcast values by default. For me the above solution would suffice.
|>
is just a function with special parsing, so you can do this (even though it doesn't really serve as a great use case for Chain.jl):
julia> functions = [(a -> a +1) (a -> a + 2); (a -> a +3) (a -> a + 4)]
2×2 Matrix{Function}:
#9 #10
#11 #12
julia> values = [0 0; 0 0]
2×2 Matrix{Int64}:
0 0
0 0
julia> @chain values begin
_ .|> functions
end
2×2 Matrix{Int64}:
1 2
3 4
# or even this
julia> @chain values begin
.|>(functions)
end
2×2 Matrix{Int64}:
1 2
3 4