How to call a vector of functions?

julia> f(x)=x^2
f (generic function with 1 method)

julia> g(x)=x+1
g (generic function with 1 method)

julia> [f,g](3)
ERROR: MethodError: objects of type Vector{Function} are not callable
Use square brackets [] for indexing an Array.
Stacktrace:
 [1] top-level scope
   @ REPL[13]:1

julia> [f,g].(3)
ERROR: MethodError: objects of type Vector{Function} are not callable
Use square brackets [] for indexing an Array.
Stacktrace:
 [1] _broadcast_getindex_evalf
   @ .\broadcast.jl:670 [inlined]
 [2] _broadcast_getindex
   @ .\broadcast.jl:643 [inlined]
 [3] getindex
   @ .\broadcast.jl:597 [inlined]
 [4] copy
   @ .\broadcast.jl:875 [inlined]
 [5] materialize(bc::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{0}, Nothing, Vector{Function}, Tuple{Int64}})
   @ Base.Broadcast .\broadcast.jl:860
 [6] top-level scope
   @ REPL[14]:1

julia>

I would expect a result as [f(3),g(3)]. How to do that? Thanks.

julia> [h(3) for h in [f,g]]
2-element Vector{Int64}:
 9
 4
3 Likes

I myself found an answer:

julia> 3 .|> [f,g]
2-element Vector{Int64}:
 9
 4

julia>
6 Likes
using Tullio

f(x)=x^2
g(x)=x+1
k=[f,g]

@tullio a[i] := k[i](3)
println(a)
1 Like

Another way is to use invoke with broadcasting, like so:

julia> f(x)=x^2
f (generic function with 1 method)

julia> g(x)=x+1
g (generic function with 1 method)

julia> v = [f,g]
2-element Vector{Function}:
 f (generic function with 1 method)
 g (generic function with 1 method)

julia> invoke.(v, Tuple{Int}, 3)
2-element Vector{Int64}:
 9
 4
1 Like