Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add foldlMaybe and code reuse #141

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions src/Data/Foldable.purs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module Data.Foldable
, maximumBy
, minimum
, minimumBy
, foldlMaybe
, null
, length
, lookup
Expand Down Expand Up @@ -436,10 +437,7 @@ maximum = maximumBy compare
-- | function. The comparison function should represent a total ordering (see
-- | the `Ord` type class laws); if it does not, the behaviour is undefined.
maximumBy :: forall a f. Foldable f => (a -> a -> Ordering) -> f a -> Maybe a
maximumBy cmp = foldl max' Nothing
where
max' Nothing x = Just x
max' (Just x) y = Just (if cmp x y == GT then x else y)
maximumBy cmp = foldlMaybe \x y -> if cmp x y == GT then x else y

-- | Find the smallest element of a structure, according to its `Ord` instance.
minimum :: forall a f. Ord a => Foldable f => f a -> Maybe a
Expand All @@ -449,10 +447,13 @@ minimum = minimumBy compare
-- | function. The comparison function should represent a total ordering (see
-- | the `Ord` type class laws); if it does not, the behaviour is undefined.
minimumBy :: forall a f. Foldable f => (a -> a -> Ordering) -> f a -> Maybe a
minimumBy cmp = foldl min' Nothing
minimumBy cmp = foldlMaybe \x y -> if cmp x y == LT then x else y

foldlMaybe :: forall f a . Foldable f => (a -> a -> a) -> f a -> Maybe a
theqp marked this conversation as resolved.
Show resolved Hide resolved
foldlMaybe f = foldl f' Nothing
theqp marked this conversation as resolved.
Show resolved Hide resolved
where
min' Nothing x = Just x
min' (Just x) y = Just (if cmp x y == LT then x else y)
f' Nothing x = Just x
f' (Just x) y = Just (f x y)

-- | Test whether the structure is empty.
-- | Optimized for structures that are similar to cons-lists, because there
Expand Down