Skip to content

Commit 41a0c7a

Browse files
committed
Update my solution to myMaximumBy and myMinimumBy
Thanks to PR #1 submitted by @RodideBoer that led me to think of it.
1 parent e732208 commit 41a0c7a

File tree

1 file changed

+2
-13
lines changed

1 file changed

+2
-13
lines changed

ch10/Rewrites.hs

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -65,21 +65,10 @@ squishAgain = squishMap id
6565
-- It takes a comparison function and a list and returns the greatest element of
6666
-- the list based on the last value that the comparison returned GT for
6767
myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
68-
myMaximumBy comp l@(x:xs) =
69-
foldr (\a b -> if comp a b == GT then a else b) x l
70-
-- It doesn't produce the desired result for:
71-
-- myMaximumBy (\_ _ -> LT) [1..10]
72-
-- => 1 (should be 10)
68+
myMaximumBy f xs = foldr (\a b -> if f a b == GT then a else b) (last xs) xs
7369

7470
-- 11
7571
-- It takes a comparison function and a list and returns the least element of
7672
-- the list based on the last value that the comparison returned LT for
7773
myMinimumBy :: (a -> a -> Ordering) -> [a] -> a
78-
myMinimumBy comp l@(x:xs) =
79-
foldr (\a b -> if comp a b == LT then a else b) x l
80-
-- It doesn't produce the desired result for:
81-
-- myMinimumBy (\_ _ -> GT) [1..10]
82-
-- => 1 (should be 10)
83-
84-
-- N.B. The only way I know how to get a value of type a is by taking the value
85-
-- from the given list because we don't know anything about the type a.
74+
myMinimumBy f xs = foldr (\a b -> if f a b == LT then a else b) (last xs) xs

0 commit comments

Comments
 (0)