Going through the magnificent Haskell Programming from first principles, I’m currently reimplementing functions from standard libraries such as maximumBy
and minimumBy
.
Here are my current versions of them:
myMaximumBy :: (a -> a -> Ordering) -> [a] -> a -- maximumBy in Data.List also throws an error on empty lists myMaximumBy _ [] = error "empty list" myMaximumBy f (x:xs) = go xs x where go [] curMax = curMax go (h:t) curMax = go t $ if (f h curMax) == GT then h else curMax -- Could be shorter, but less readable with bool from Data.Bool: -- go (h:t) curMax = go t $ bool curMax h (f h curMax == GT) myMinimumBy :: (a -> a -> Ordering) -> [a] -> a myMinimumBy f = myMaximumBy $ \x y -> negateOrdering $ f x y where negateOrdering EQ = EQ negateOrdering LT = GT negateOrdering GT = LT
I know they’re not total functions, but I’ll get to rewriting them with something like Maybe
later on.
What I’m more curious about is whether it’s a problem to define myMinimumBy
through myMaximumBy
using negateOrdering
; could this be a problem for some implementations of the ordering function f
?
Additionaly to takes on the question in the last paragraph, I’m happy for any kind of feedback on how to make the code shorter, more readable, or more idiomatic.