Friday 29 April 2016

Haskell: where clause

Most of the times we need intermediate results to get the final outcome, By using where clause we can define intermediate results.


Suppose if a triangle has sides a, b and c. As per Herons’s formula, following formula is used to calculate area of triangle.
Where s is semi perimeter.
triangle.hs

areaOfTriangle a b c = sqrt (s * (s - a) * (s - b) * (s - c))
    where
    s = (a + b + c) / 2


*Main> :load triangle.hs
[1 of 1] Compiling Main             ( triangle.hs, interpreted )
Ok, modules loaded: Main.
*Main> areaOfTriangle 40 40 20
387.2983346207417


Examples
1. Find sum of squares of two numbers
Sample.hs    
sumSquares :: Integer -> Integer -> Integer
sumSquares x y = xSquare + ySquare
                 where
                     xSquare = x * x
                     ySquare = y * y


Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> sumSquares 10 20
500
*Main> sumSquares 1 2
5
*Main> sumSquares 3 4
25


2. Implement (a+b) whole square function
Sample.hs

aPlusBWholeSquare :: Integer -> Integer -> Integer
aPlusBWholeSquare a b = aSquare + bSquare + twiceAB
                 where
                     aSquare = a * a
                     bSquare = b * b
                     twiceAB = (2 * a * b)


Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> aPlusBWholeSquare 1 2
9
*Main> aPlusBWholeSquare 3 4
49


You can include where clause inside other where clause. For example, above program can be written like below.

Sample.hs

aPlusBWholeSquare :: Integer -> Integer -> Integer
aPlusBWholeSquare a b = aSquare + bSquare + twiceAB
                 where
                     aSquare = a * a
                     bSquare = b * b
                     twiceAB = 2 * prod
                         where
                             prod = a * b


Note
a.   The definition of where clause applies to the code that precedes it.
b.   Where and local variable definitions are indented by 4 spaces.

Previous                                                 Next                                                 Home

No comments:

Post a Comment