Thursday, August 17, 2017

Julia - Language - Functions - Multiple Expression Functions

The single expression function can perform atmost one calculation for us. If we wanted to calculate more, then we have to use 'Multiple Expression Function.

$ 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 muply(x,y)
       println("\n First Value = $x ; Second Value = $y. \n $x x $y =  ")
       return x*y
       end
muply (generic function with 1 method)

Note that we have used the keyword function to create this function. Also, this function is having a name. 

julia> methods(muply)
# 1 method for generic function "muply":
muply(x, y) in Main at REPL[4]:2

julia> muply
muply (generic function with 1 method)

julia> muply(4,8)

 First Value = 4 ; Second Value = 8. 
 4 x 8 =  
32

julia> 



Now Let us create a Multiple Expression Function and try to return without a return keyword.

julia> function muplyadd(x,y)
       println("\n First Value = $x ; Second Value = $y. \n $x x $y =  ")
       x*y
       x+y
       end
muplyadd (generic function with 1 method)

julia> muplyadd(4,5)

 First Value = 4 ; Second Value = 5. 
 4 x 5 =  
9

julia> 

As we see, when we do not use the return keyword, Julia will return only the result of the last expression. Now, to return output of the result of multiple expression, we can separate the result expressions with comma:

julia> function muplyadd(x,y)
       println("\n First Value = $x ; Second Value = $y. \n ")
       x*y,x+y

       end
muplyadd (generic function with 1 method)

julia> muplyadd(4,5)

 First Value = 4 ; Second Value = 5. 

(20, 9)

julia> 

We see when the return expressions are separated by a comma the output is returned as a tuple. 

No comments:

Post a Comment