-
Notifications
You must be signed in to change notification settings - Fork 26
Open
Description
Recently I needed a way to find the index of the maximum element in a list, and I was surprised that there was not an indexed counterpart to maximumOf. I came up with the following, which I thought could also be generally useful to have in optics:
newtype IxMin i a = IxMin { getIxMin :: Maybe (a, i) }
deriving (Semigroup, Monoid) via Maybe (Min (a, i))
iminimumOf
:: (Is k A_Fold, is `HasSingleIndex` i, Ord a, Ord i)
=> Optic' k is s a -> s -> Maybe (i, a)
iminimumOf o = fmap swap . getIxMin . ifoldMapOf o (curry (IxMin . Just . swap))
newtype IxMax i a = IxMax { getIxMax :: Maybe (a, i) }
deriving (Semigroup, Monoid) via Maybe (Max (a, Down i))
imaximumOf
:: (Is k A_Fold, is `HasSingleIndex` i, Ord a, Ord i)
=> Optic' k is s a -> s -> Maybe (i, a)
imaximumOf o = fmap swap . getIxMax . ifoldMapOf o (curry (IxMax . Just . swap))I wrote them such that if there exists multiple maximum elements, the one with the "lesser" index is returned:
>>> iminimumOf ifolded "calamari"
Just (1,'a')Is it desirable to have these in the library? If so, I can prepare a PR for them.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels