Friday 29 April 2016

Haskell: let expression

It is another syntactic sugar just like where clause. By using let expression, you can define variables and use them in other expressions.

Syntax
let <bindings> in <expression>

The variables you define in bindings section are accessed by the expression after ‘in’ part.


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

triangle.hs
areaOfTriangle a b c = 
    let 
        s = (a + b + c) / 2
    in
        sqrt (s * (s - a) * (s - b) * (s - c))

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


By using let clause, you can define functions that are in local scope.
*Main>  [let cube x = x * x * x in [cube 2, cube 3, cube 5, cube 7]]  
[[8,27,125,343]]


You can bind multiple variables in let clause.

processData.hs

process x = 
    let
        a = 10
        b = 20
        c = 30
    in
        ((x * a) * (b+c))


*Main> process 10
5000
*Main> 
*Main> process 20
10000


If you want to bind several variables on same line, separate them using semi colon (;).

*Main> let process x = (let a = 10;b = 20;c = 30 in ((x * a) * (b+c)))
*Main> 
*Main> process 10
5000
*Main> 
*Main> process 20
10000




Previous                                                 Next                                                 Home

No comments:

Post a Comment