10

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.

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

1 Comment

f.(args...) is equivalent to broadcast(f, args...). You are wrapping your function in an anonymous function and can also be done with the dot-syntax for broadcasting: ((x, y) -> Foo(x, b=y).([1,2,3], [4,5,6])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.