Monday 6 June 2016

Haskell : Find maximum in list of numbers


ListUtil.hs
module ListUtil(getMaximum) where
    getMaximum :: [Integer] -> (Maybe Integer)
    getMaximum [] = Nothing
    getMaximum (x:xs) = Just (getMax x xs)

    getMax :: Integer -> [Integer] -> Integer
    getMax currentMax [] = currentMax
    getMax currentMax (x:xs)
      | (currentMax < x) = getMax x xs
      | otherwise = getMax currentMax xs

*ListUtil> :load ListUtil.hs
[1 of 1] Compiling ListUtil         ( ListUtil.hs, interpreted )
Ok, modules loaded: ListUtil.
*ListUtil> 
*ListUtil> getMaximum [1, 20, 98, 3, 4, 987, 123, 432]
Just 987
*ListUtil> 
*ListUtil> getMaximum []
Nothing



Previous                                                 Next                                                 Home

No comments:

Post a Comment