Reputation: 14551
I have seen the following in other people's code, but I've never written it in my own since I didn't understand what was happening.
As an example:
function add(x::T, y::T) where {T :< Integer}
I am guessing that T
is being cast as an Integer and then used to explicitly type x
and y
. But why not just do x::Int64
? Does where {T :< Integer}
allow for any Int type like Int32
and Int64
?
Upvotes: 6
Views: 190
Reputation: 505
To expand a little on Oscar's answer:
Using function add(x::T, y::T) where {T :< Integer}
allows you to add a parametric method to the function add(x, y)
. You can read up on this in more detail in the Julia documentation under Parametric Methods.
This comes with two big advantages:
It allows you to define reasonably general methods (since in many cases the exact type of integer would not really affect the function definition). Simultaneously it allows you to restrict the call to x, y
pairs of the same type, which can improve type stability and lead to more efficient compiled code.
Upvotes: 6
Reputation: 6398
function add(x::T, y::T) where {T :< Integer}
means that the function can be called on any 2 variables who's type is the same subtype of Integer
. This includes things like 2 bigInt
s, but not 1 Int64
and 1 Int32
. This is called Diagonal Dispatch, and is a very useful pattern.
Upvotes: 4