Skip to content

Idea: imaximumOf and iminimumOf #536

@ozkutuk

Description

@ozkutuk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions