Norman
Norman

Reputation: 310

Julia: Broadcasting Functions with Keyword Arguments

Suppose we have a composite type:

mutable struct MyType{TF<:AbstractFloat, TI<:Integer}
a::TF
b::TF
end

We define a constructor

function MyType(a; b = 1.0)
    return MyType(a, b)
end

I can broadcast MyType over an array of a's, but how can I do that for b's?

I tried to do

MyType.([1.0, 2.0, 3.0]; [:b, 1.0, :b, 2.0, :b, 3.0,]) 

But, this does not work.

Note that the above example is totally artificial. In reality, I have a composite type that takes in many fields, many of which are constructed using keyword arguments, and I only want to change a few of them into different values stored in an array.

Upvotes: 10

Views: 969

Answers (1)

fredrikekre
fredrikekre

Reputation: 10984

I don't think you can do this with dot-notation, however, you can manually construct the broadcast call:

julia> struct Foo
           a::Int
           b::Int
           Foo(a; b = 1) = new(a, b)
       end

julia> broadcast((x, y) -> Foo(x, b = y), [1,2,3], [4,5,6])
3-element Array{Foo,1}:
 Foo(1, 4)
 Foo(2, 5)
 Foo(3, 6)

julia> broadcast((x, y) -> Foo(x; y), [1,2,3], [:b=>4,:b=>5,:b=>6])
3-element Array{Foo,1}:
 Foo(1, 4)
 Foo(2, 5)
 Foo(3, 6)

Upvotes: 9

Related Questions