How to define a function whose type is variable?

I am currently working to implement new sparse matrix formats for faster matrix-vector products. I want to preserve some features of the current CSR implementation in Julia. In particular, I would like to define functions and structs whose data have variable types, i.e., Tv and Ti.

In particular, I looked at this old piece of Julia code from SparseMatrices with the following signature:

function csr2csc{Tv,Ti}(indptr::Vector{Ti}, indval::Vector{Ti}, nzval::Vector{Tv}, m::Int, n::Int)

Similarly, I try to define the following function:

function test{Ti}(x::Vector{Ti})
return sum(x)
end

However, when I run this code, I get the error UndefVarError: Ti not defined. So I wonder how to define functions like csr2csc given above with variable types Tv and Ti.

The common syntax is

function test(x::Vector{Ti}) where {Ti}
   return sum(x)
end

# and for structs

struct YourStruct{T}
   x::T
end

Note that often you don’t even need to specify the type! E.g. if you don’t rely on multiple dispatch, then you don’t need to overly specify the types of function inputs. Different for structs, where parametric types often improve type stability.

2 Likes

Or

function test(x::Vector)
   return sum(x)
end
5 Likes