# How to define a function whose type is variable?

**URL:** <https://discourse.julialang.org/t/how-to-define-a-function-whose-type-is-variable/100744>\
**Category:** General Usage\
**Created:** [June 23, 2023, 3:18pm UTC](https://discourse.julialang.org/t/how-to-define-a-function-whose-type-is-variable/100744 "2023-06-23T15:18:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nvenkov1](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nvenkov1/32/43679_2.png) [@nvenkov1](https://discourse.julialang.org/u/nvenkov1)\
**Post date:** [June 23, 2023, 3:18pm UTC](https://discourse.julialang.org/t/how-to-define-a-function-whose-type-is-variable/100744/1 "2023-06-23T15:18:44Z")

</div>

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`.

---

<div class="post-metadata">

**Author:** ![SteffenPL](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/steffenpl/32/206270_2.png) [@SteffenPL](https://discourse.julialang.org/u/SteffenPL)\
**Post date:** [June 23, 2023, 3:23pm UTC](https://discourse.julialang.org/t/how-to-define-a-function-whose-type-is-variable/100744/2 "2023-06-23T15:23:53Z")

</div>

The common syntax is

```julia
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.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [June 23, 2023, 3:40pm UTC](https://discourse.julialang.org/t/how-to-define-a-function-whose-type-is-variable/100744/3 "2023-06-23T15:40:58Z")

</div>

> [@SteffenPL](#):
>
> ```julia
> function test(x::Vector{Ti}) where {Ti}
> return sum(x)
> end
> 
> ```

Or

```julia
function test(x::Vector)
   return sum(x)
end

```
