Interpolating Keyword Arguments in Julia

I have been given a form function

f(;a=1, b=2, c=3, d=4) = ...

and also a vector of length 4, containing logical values ​​indicating which keyword arguments to enter, and then also a vector of length from 1 to 4 values ​​for entering into the corresponding slots (in order). For example, I may be given

[true,false,true,false]
[5,100]

so then I want the following to be evaluated:

f(a=5, c=100)

How do I do this efficiently and elegantly?

+4
source share
1 answer

You can use a combination of logical indexing, zip and a keyword from the list (Symbol, Any):

julia> f(;a=1,b=2,c=3,d=4) = @show a,b,c,d
f (generic function with 1 method)

julia> ks = [:a,:b,:c,:d]
4-element Array{Symbol,1}:
 :a
 :b
 :c
 :d

julia> shoulduse = [true,false,true,false]
4-element Array{Bool,1}:
  true
 false
  true
 false

julia> vals = [5,100]
2-element Array{Int64,1}:
   5
 100

julia> kw = zip(ks[shoulduse], vals)
Base.Zip2{Array{Symbol,1},Array{Int64,1}}([:a,:c],[5,100])

julia> f(;kw...)
(a,b,c,d) = (5,2,100,4)
(5,2,100,4)
+8
source

All Articles