Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating keyword arguments in Julia

Tags:

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?

like image 350
Thoth Avatar asked Feb 08 '23 04:02

Thoth


1 Answers

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)
like image 81
Tom Breloff Avatar answered Feb 16 '23 16:02

Tom Breloff