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. -}
This entry was posted
on Tuesday, May 22nd, 2007 at 12:26 pm and is filed under Haskell - SOE.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.