Julia: Broadcasting Functions with Keyword Arguments

梦想与她 提交于 2021-02-04 17:31:06

问题


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:


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)


来源:https://stackoverflow.com/questions/48738016/julia-broadcasting-functions-with-keyword-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!