使结构可调用时出现 Subype 问题

问题描述 投票:0回答:1

我正在尝试使矩阵可调用,以便能够将其用作例如变换函数的矩阵。我想出了以下方法,效果很好。

rotation = [cos (x->-sin(x)) ; sin cos]

function (z::Matrix{Function})(x)
map(f->f(x), z)
end

rotate_pi_6 =  rotation(π/6)
rotate_pi_6 * [1,1]
#2-element Vector{Float64}:
# 0.36602540378443876
# 1.3660254037844386

到目前为止,一切都很好。 但是,我发现如果所有功能都相同,那么代码就不再有效。

[cos cos;cos cos](1)
   > ERROR: MethodError: objects of type Matrix{typeof(cos)} are not callable
   > Use square brackets [] for indexing an Array.
   > Stacktrace:
   >  [1] top-level scope
   >    @ REPL[109]:1

看来由于我们现在有一个 Matrix{typeof(cos)} 而不是一个 Matrix{Function},所以没有找到合适的调度。然而我希望这能起作用,因为我想象“cos”是“函数”的子类型。

我在尝试时发现了这一点

trm = [0 1 ; 2 3]
fn_pwr = n->x->x^n
trfm = map(fn_pwr, trm)
trfm(2)

> ERROR: MethodError: objects of type Matrix{var"#18#20"{Int64}} are not callable, etc...

我期望类似 [1 2 ; 4 8]

欢迎任何建议、更正、想法、指点。

types julia
1个回答
0
投票

您的方法应定义为:

function (z::Matrix{<:Function})(x)
   map(f->f(x), z)
end

比你能做的:

julia> [cos cos](0)
1×2 Matrix{Float64}:
 1.0  1.0

说明

© www.soinside.com 2019 - 2024. All rights reserved.