Saturday, 30 April 2016

Haskell: Combine where and guards

You can use where clause and guards together.


Lets try to solve number of roots to a quadratic equation.
The discriminant tells you about the "nature" of the roots of a quadratic equation given that a, b and c are rational numbers, number of roots for the quadratic equation.

Discriminant = b^2 - 4*a*c

if Discriminant > 0 then number of roots are 2.
if Discriminant = 0 then number of roots are 1, else 0.

discriminant.hs
roots a b c
    | (descriminant > 0)  = 2
    | (descriminant == 0) = 1
    | otherwise = 0
        where
        descriminant = b^2 - 4*a*c

*Main> :load discriminant.hs
[1 of 1] Compiling Main             ( discriminant.hs, interpreted )
Ok, modules loaded: Main.
*Main> roots 1 6 8
2
*Main> roots 1 6 9
1
*Main> roots 1 6 10
0




Previous                                                 Next                                                 Home

No comments:

Post a Comment