Friday, 29 April 2016

Haskell: Functions

Function takes some input and produce output by processing the input. By using functions we can reuse the code. Variables and function names must always start with lower case letter.

For example,
square(x) = x * x
cube(x) = x * x * x

How to define a function in Haskell
Function_name arg1 arg2 … argN = function body

Function
Definition in Haskell
square(x) = x * x
square x = x * x
cube(x) = x * x * x
cube x = x * x * x


arithmetic.hs
{-Simple Haskell program todemonstrate Arithmetic operations -}
addition x y = x + y
subtraction x y = x - y
multiplication x y = x * y

square x = x * x
cube x = x * x * x


You can call the function by using function name preceded by arguments.
*Main> :load arithmetic.hs
[1 of 1] Compiling Main             ( arithmetic.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> addition 10 134
144
*Main> 
*Main> subtraction 23 45
-22
*Main> 
*Main> multiplication 43 76
3268
*Main> 
*Main> square 10
100
*Main> 
*Main> cube 123
1860867
*Main> 
*Main> cube 32
32768
*Main> 


Functions in Haskell takes precedence over other operators like *, +, - etc.,

*Main> addition 5 6 * 1
11
*Main> addition 5 6 * 2
22
*Main> addition 5 6 * 3
33
*Main> addition 5 6 * 4
44

In Haskell, functions can be arguments to other functions, I will explain about this later.

Following are the naming conventions to a function in Haskell
a.   Function name must start with a lower case letter.
b.   List of parameters to a function also start with a lower case letter
c.    Better to follow camel case convention, while defining function name, parameter names.
Ex:
sumOfNumbers arg1 arg2 = arg1 + arg2
interestCalc rateOfInterest principle time = (rateOfInterest * principle* time ) / 100


Previous                                                 Next                                                 Home

No comments:

Post a Comment