Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the `where {t :< Integer}` mean in the context of a function declaration in Julia?

Tags:

julia

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?

like image 975
logankilpatrick Avatar asked Sep 27 '19 15:09

logankilpatrick


People also ask

How is Julia function defined?

The basic syntax for defining functions in Julia is: julia> function f(x,y) x + y end f (generic function with 1 method) This function accepts two arguments x and y and returns the value of the last expression evaluated, which is x + y . There is a second, more terse syntax for defining a function in Julia.

What is the type of a function in Julia?

Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.

How do you declare a variable in Julia?

Variables in Julia can be declared by just writing their name. There's no need to define a datatype with it. Initializing variables can be done at the time of declaring variables. This can be done by simply assigning a value to the named variable.

What is function declaration and definition?

The function declaration (function statement) defines a function with the specified parameters. You can also define functions using the Function constructor and a function expression.


2 Answers

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.

like image 139
Wolf Avatar answered Oct 26 '22 15:10

Wolf


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 bigInts, but not 1 Int64 and 1 Int32. This is called Diagonal Dispatch, and is a very useful pattern.

like image 25
Oscar Smith Avatar answered Oct 26 '22 17:10

Oscar Smith