Friday, 26 February 2016

Julia: functions

Function is blocks of statements that take zero or more arguments, do processing and return none, one or more values.

Syntax
function f(arg1, arg2,...argN)
  # Do some processing

end

julia> function sum(a,b)
           return a+b
       end
sum (generic function with 1 method)

julia> print(sum(10,20))
30
julia> print(sum(10,23))
33


Function is an object in Julia, so you can assign function to any variable and use it.
julia> addition=sum
sum (generic function with 1 method)

julia> addition(1,3)
4

julia> addition(1,33)
34


If the body of the function contains only one expression, then you can define function in compact way like below.
julia> sum(x,y,z)=x+y+z
sum (generic function with 2 methods)

julia> sum(10,20,30)
60


Note:
a.   All the arguments to function other than numbers and characters are passed by reference. So changes to the arguments inside a function reflect outside also.
b.   You can use Unicode characters also as function names.
julia> ∑(x,y,z) = x + y +z
∑ (generic function with 1 method)

julia> ∑(10, 20, 30)
60





Previous                                                 Next                                                 Home

Thursday, 25 February 2016

Julia: Compound expressions

By using compound expression, we can evaluate multiple expressions in one block.

Syntax
begin
   expression1
   expression2
         …..
         …..
   expression

end

julia> result=begin
               a=10
               b=20
               c=30
               a=a+b
               b=a*c
               b
       end
900

julia> result
900



Previous                                                 Next                                                 Home