Monday, 6 June 2016

Haskell: get maximum and minimum in list of numbers


ListUtil.hs
module ListUtil(getMaxMin) where
    getMaxMin :: [Integer] -> Maybe (Integer, Integer)
    getMaxMin [] = Nothing
    getMaxMin (x:xs) = Just (findMaxMin x x xs)


    findMaxMin :: Integer -> Integer -> [Integer] -> (Integer, Integer)
    findMaxMin currentMax currentMin [] = (currentMax, currentMin)
    findMaxMin currentMax currentMin (x:xs)
        | (currentMax < x) = findMaxMin x currentMin xs
        | (currentMin > x) = findMaxMin currentMax x xs
        | otherwise = findMaxMin currentMax currentMin xs

*ListUtil> :load ListUtil.hs
[1 of 1] Compiling ListUtil         ( ListUtil.hs, interpreted )
Ok, modules loaded: ListUtil.
*ListUtil> 
*ListUtil> getMaxMin [1]
Just (1,1)
*ListUtil> 
*ListUtil> getMaxMin []
Nothing
*ListUtil> 
*ListUtil> getMaxMin [2, 3, 5, 100, 98, -9, 10]
Just (100,-9)
*ListUtil> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment