Specifying type variables

When we define a parametric method, we use the where clause to introduce type variables. Let's go over a simple example:

triple(x::Array{T,1}) where {T <: Real} = 3x

The triple function takes an Array{T}, where T is any subtype of Real. This code is very readable, and it is the format that most Julia developers choose to specify type parameters. So what could the value of T be? Could it be a concrete type, abstract type, or both?

To answer this question, we can test it out from the REPL:

So the method does get dispatched on both the abstract type (Real) and concrete type (Int64). It is worth mentioning that the where clause can also be placed right next to the method argument:

triple(x::Array{T,1} where {T <: Real}) = 3x

From a functional perspective, it is the same as before, whether the where clause is placed inside or outside.

There are some subtle differences, however. When the where clause is placed outside, you gain two additional benefits:

  • The type variable T is accessible inside the method body.
  • The type variable T can be used to enforce the same values if it is used for multiple method arguments.

It turns out that the second point leads to an interesting feature in Julia's dispatch system. We will go over this next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset