Monday, August 28, 2017

Julia - Language - Functions - Type parameters as function input

There is a facility in Julia, by which we can restrict a function to accept only certain datatypes. This helps to tighten our code and also improves the performance.

 $ julia
               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-pc-linux-gnu

julia> function myFunc(myIntInput::Int)
       return 5*myIntInput
       end
myFunc (generic function with 1 method)

julia> myFunc(4.0)
ERROR: MethodError: no method matching myFunc(::Float64)
Closest candidates are:
  myFunc(::Int64) at REPL[1]:2

julia> myFunc(4)
20

julia> methods(myFunc)
# 1 method for generic function "myFunc":
myFunc(myIntInput::Int64) in Main at REPL[1]:2

julia> 


We can even include the type information in the method definition:

julia> function myArgTest{T<:Real}(x::T)
       print("The value $x is of type $T")
       end
myArgTest (generic function with 1 method)

julia> 


Explanation of this function:
The curly braces {}, is placed in between the function name and the argument paranthesis. T is used by convention. In the above function definition we have used the {T<:Real} syntax. That means that allow only Real or any subtype of Real. We can be more specific, say - only allow integers 
{T::Int}.

julia> myArgTest(5.6)
The value 5.6 is of type Float64
julia> myArgTest(pi)
The value π = 3.1415926535897... is of type Irrational{:π}
julia>  myArgTest(4)
The value 4 is of type Int64
julia> myArgTest(4//9)
The value 4//9 is of type Rational{Int64}
julia> myArgTest(4/9)
The value 0.4444444444444444 is of type Float64
julia> 


Here is an example of using two arguments that can be of any type, as long as they are the same. 

julia> function myTypeAdd{T}(a::T,b::T)
              return +(a,b)
              end
myTypeAdd (generic function with 1 method)

julia> 

Let us now add two complex numbers:

julia> myTypeAdd(4+3im,0+2im)
4 + 5im

julia>

Now let us try to add one complex number to an integer:

julia> myTypeAdd(4+3im,0)
ERROR: MethodError: no method matching myTypeAdd(::Complex{Int64}, ::Int64)
Closest candidates are:
  myTypeAdd(::T, ::T) where T at REPL[15]:2

julia> 


as expected, Julia has thrown an error.

By, this we have demostrated how to tighten up your code using Julia.

No comments:

Post a Comment