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”
The following also works…
maxList (x0:xs) = foldr max x0 xs
minList (x0:xs) = foldr min x0 xs
maxList = foldr1 max
minList = foldr1 min