Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

types - Accepting all vectors of matrices of numbers as a function argument in Julia

I'm attempting to write a function that takes a vector of matrices and calculates their product recursively. The function itself goes something like this:

using LinearAlgebra: I

"""
Recursively calculates the product of the matrices in a given vector `V`.
"""
function ∏_(V)
    if length(V) == 1
        return V[1]
    elseif length(V) == 0
        UniformScaling(1)
    else
        V[1] * ∏_(V[2:end])
    end
end

This is all fine and dandy, but I would like to limit the types of the input to something like

V::Vector{Matrix{Number}} ,

where Number could be any field element (an integer, a rational or a complex number). How might I achieve this with Julia's type annotations? I know of the subtype operator <:, but writing

V::Vector{Matrix{<:Number}}

simply produces the error

ERROR: LoadError: MethodError: no method matching ∏_(::Array{Array{Rational{Int64},2},1})
Closest candidates are:
    ∏_(::Array{Array{var"#s1",2} where var"#s1"<:Number,1})

when giving the function an array of rational integer matrices. How might I fix this?

question from:https://stackoverflow.com/questions/66062734/accepting-all-vectors-of-matrices-of-numbers-as-a-function-argument-in-julia

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to specify V::Vector{<:Matrix{<:Number}}

However, you can extend it further to allow more uses, for example

V::AbstractVector{<:AbstractMatrix{<:Number}}
V::AbstractVector{<:AbstractMatrix}
V::AbstractVector
V::Any

It probably doesn't harm anyone and might allow futures uses you don't even imagine right now


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...