Saturday 4 June 2016

Haskell: Find middle number

Suppose you had numbers like 10, 35, 15 then the middle number should be 15, since it is in between 10 and 35.


Sample.hs
{- Return True if x is inbetween y and z else False-}
between :: Int -> Int -> Int -> Bool
between x y z = (x >= y && x <= z) || (x >= z && x <= y)

getMiddleNumber :: Int -> Int -> Int -> Int
getMiddleNumber x y z
    | between x y z = x
    | between y z x = y
    | otherwise = z

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getMiddleNumber 10 35 15
15
*Main> getMiddleNumber 10 10 10
10
*Main> getMiddleNumber 10 9 19
10
*Main> getMiddleNumber 1 3 2
2


Previous                                                 Next                                                 Home

No comments:

Post a Comment