SOE ex.5.6


maxList :: Ord a => [a] -> a
maxList [] = error "Must at least have one element."
maxList [x] = x
maxList (x:xs) = let y = maxList(xs)
                 in if x > y then x else y

minList :: Ord a => [a] -> a
minList [] = error "Must at least have one element."
minList [x] = x
minList (x:xs) = if x < y then x else y
                 where y = minList xs

maxList' :: Ord a => [a] -> a
maxList' = foldl1 max

minList' :: Ord a => [a] -> a
minList' = foldr1 min

{- instead of empty list returns error, we could return Maybe type -}
maxList'' :: Ord a => [a] -> Maybe a
maxList'' [] = Nothing
maxList'' (x:xs) = Just $ foldl max x xs

minList'' :: Ord a => [a] -> Maybe a
minList'' [] = Nothing
minList'' (x:xs) = Just $ foldr min x xs

{- Note: there is Perlude’s maximum and minimum funtions for maxList and minList. -}

Leave a Reply