Most of the times we need intermediate
results to get the final outcome, By using let..in block we can define
intermediate results in let block and perform main calculations in ‘in’ block.
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_area.hs [1 of 1] Compiling Main ( triangle_area.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> areaOfTriangle 40 40 20 387.2983346207417
Following
application find the roots of polynomial application.
roots.hs
roots a b c = let discriminant = sqrt (b * b - 4 * a * c) in ((-b + discriminant) / (2 * a), (-b - discriminant) / (2 * a))
*Main> :load roots.hs [1 of 1] Compiling Main ( roots.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> roots 10 100 5 (-5.0252531694167143e-2,-9.949747468305834)
You can declare
multiple variables in let clause.
letEx.hs
processData x = let a = 10 b = 20 in if (x < 0) then (a+b) else (a+b*x)
Prelude> :load letEx.hs [1 of 1] Compiling Main ( letEx.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> processData 0 10 *Main> *Main> processData 1 30 *Main> processData 2 50 *Main>
Shadowing
We can insert a let block inside another
let block, If we repeat the same variable name in inner let expression, it
hides the variable defined in outer let expression.
letEx.hs
processData x = let a = 10 b = 20 in if (x < 0) then let a = 20 in (a, b) else let b = 30 in (a, b)
*Main> :load letEx.hs [1 of 1] Compiling Main ( letEx.hs, interpreted ) Ok, modules loaded: Main. *Main> *Main> processData (-10) (20,20) *Main> *Main> processData 10 (10,30) *Main>
When I call the function processData
(-10), it returns (20, 20), since variable a is assigned to 20 in inner let
block, which hides a=10 in outer let block.
No comments:
Post a Comment