Exercise 5.6

Perhaps it was the C++ programmer in me who immediately thought about maximum/minimum integers as the initial values for these functions.

maxList :: [Int] -> Int
maxList xs = foldl maxop (minBound::Int) xs
    where maxop x y = if (x < y) then y else x
maxList' xs = maxop xs minBound::Int
    where maxop (x:xs) m = if (x < m)
                           then maxop xs m
                           else maxop xs x
          maxop [] m = m
minList :: [Int] -> Int
minList xs = foldl minop (maxBound::Int) xs
    where minop x y = if (x < y) then x else y
minList' xs = minop xs maxBound::Int
    where minop (x:xs) m = if (x > m)
                           then minop xs m
                           else minop xs x
          minop [] m = m

2 Responses to “Exercise 5.6”

  1. alix says:

    The following also works…

    maxList (x0:xs) = foldr max x0 xs

    minList (x0:xs) = foldr min x0 xs

  2. Josh Nahum says:

    maxList = foldr1 max
    minList = foldr1 min

Leave a Reply