Monday, August 28, 2017

Julia - Language - Functions - Stabby and Do construct to create anonymous functions

There are two types of anonymous functions in Julia:

  1. Stabby Functions
  2. Do Block


These are quick and dirty functions. They are called anonymous functions as they have no name. That means we cannot call these functions later - the way we do for other functions. 

Examples:

$ 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> y -> 3y^2 + 2y -2
(::#1) (generic function with 1 method)

julia> 

Since, the stabby function cannot be called - we can use the map() function to apply the values in an array to this stabby function. 

julia> map(y -> 3y^2 + 2y -2,[1,2,3,4,5])
5-element Array{Int64,1}:
  3
 14
 31
 54
 83

julia> 


Using do to create anonymous function:

julia> map([1,2,3,4,5]) do y
              3y^2 + 2y -2 
              end
5-element Array{Int64,1}:
  3
 14
 31
 54
 83

julia> 


 The beauty of do statement is that we can add else clause to it. 

julia> map([3,6,9,10,11]) do y
              if mod(y,3) == 0
                100y
              elseif mod(y,3) == 1
                200y
              else
                mod(y,3) == 2
                300y
              end
              end
5-element Array{Int64,1}:
  300
  600
  900
 2000
 3300

julia> 

No comments:

Post a Comment