Set
Set

Reputation: 944

Interpolating keyword arguments in Julia

I'm given a function of the form

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

as well as a vector of length 4 containing boolean values indicating which keyword arguments need to be inputed, and then also a vector of length between 1 and 4 of the values to enter in the appropriate slots (in order). For instance I might be given

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

such that then I want the following evaluated:

f(a=5, c=100)

How do I do this efficiently and elegantly?

Upvotes: 4

Views: 121

Answers (1)

Tom Breloff
Tom Breloff

Reputation: 1802

You could use a combination of boolean indexing, zip, and keyword splatting from a list of (Symbol,Any) pairs:

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)

Upvotes: 8

Related Questions