Home > OS >  How to write the types for this generic / parametric function with constraint
How to write the types for this generic / parametric function with constraint

Time:08-27

Code like the following doesn't work. I suspect it is due to covariance of type parameters.

What is the best way to write the type of the following function so it works with both dense & sparse matrix?

using LinearAlgebra
using SparseArrays


function test(A::Adjoint{T, AbstractMatrix{T}}) where T <: Real
    @show 1
end


x = sparse(rand(5, 5))
test(x')

# MethodError: no method matching test(::Adjoint{Float64, SparseMatrixCSC{Float64, Int64}})

CodePudding user response:

function test(A::Adjoint{T, M}) where {T<:Real, M<:AbstractMatrix{T}}
    @show 1
end

CodePudding user response:

I initially misunderstood your requirement. So this, as DNF suggested, would work for dense and sparse adjoint matrices:

function test(A::Adjoint{T, <:AbstractMatrix{T}}) where T <: Real
    @show 1
end

x = sparse(rand(5, 5))
julia> test(x')
1 = 1
1
  • Related