Julia - Is it possible to do a vectorized call on a struct or function by a keyword argument?

Viewed 115

Is it possible to do an efficient and elegant vectorized call on a function or struct by a single (or few) keyword arguments? Something like this

F(;x=10, y=20) = y + x

Base.@kwdef struct S
    x = 10
    y = 20
end

F.(y=1:20) # doesn't work
S.(y=1:20) # doesn't work

PS. I know I can do this in a for loop

1 Answers

You can use anonymous function as a wrapper

julia> F(; x = 10, y = 10) = x + y
julia> (y -> F(y = y)).(1:20)
20-element Vector{Int64}:
 11
 12

julia> Base.@kwdef struct S
           x = 10
           y = 20
       end

julia> (y -> S(y = y)).(1:20)
20-element Vector{S}:
 S(10, 1)
 S(10, 2)
 S(10, 3)
Related