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
?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With