Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Equivalent of .|> for array of functions #35

Open
koalp opened this issue Sep 16, 2021 · 2 comments
Open

Equivalent of .|> for array of functions #35

koalp opened this issue Sep 16, 2021 · 2 comments

Comments

@koalp
Copy link

koalp commented Sep 16, 2021

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.

@filchristou
Copy link

filchristou commented Nov 25, 2021

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.

@jkrumbiegel
Copy link
Owner

jkrumbiegel commented Nov 25, 2021

|> 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants