colinfang
colinfang

Reputation: 21737

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

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}})

Upvotes: 0

Views: 76

Answers (2)

AboAmmar
AboAmmar

Reputation: 5559

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

Upvotes: 1

Elias Carvalho
Elias Carvalho

Reputation: 296

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

Upvotes: 1

Related Questions