本文介绍了朱莉娅:广播功能与关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个复合类型:
Suppose we have a composite type:
mutable struct MyType{TF<:AbstractFloat, TI<:Integer}
a::TF
b::TF
end
我们定义一个构造函数
function MyType(a; b = 1.0)
return MyType(a, b)
end
我可以通过a
的数组广播MyType
,但是如何为b
进行广播?
I can broadcast MyType
over an array of a
's, but how can I do that for b
's?
我试图做
MyType.([1.0, 2.0, 3.0]; [:b, 1.0, :b, 2.0, :b, 3.0,])
但是,这不起作用.
请注意,以上示例完全是人为的.实际上,我有一个复合类型,它包含许多字段,其中许多字段是使用关键字参数构造的,我只想将其中的一些更改为存储在数组中的不同值.
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.
推荐答案
我认为您不能使用点符号来完成此操作,但是,您可以手动构建广播呼叫:
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)
这篇关于朱莉娅:广播功能与关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!