Skip to content

minimumOn function #331

Description

@Boarders

It would be nice to have a minimumOn function of the form:

minimumOn :: (Ord b, Generic.Vector v a) => (a -> b) -> v a -> a 

A possible implementation could just adapt the existing one for minimumBy:

minimumOn :: (Ord b, Vector v a) => (a -> b) -> v a -> a
{-# INLINE minimumOn #-}
minimumOn f = Bundle.foldl1' minBy . stream
  where
    {-# INLINE minBy #-}
    minBy x y = case compare (f x) (f y) of
                  GT -> y
                  _  -> x

Activity

  1. lehins commented on Sep 21, 2020

    @lehins
    Contributor

    @Boarders I can see how such function can be useful (especially for Storable, Unbox and Prim, when b doesn't have an instance, while a does), but there is a problem with your suggested implementation. Namely function f will be evaluated 2*n - 1 times and in case when f is really expensive this could be very noticeable.

    A possibly better solution would be to first zip with that function over:

    minimumOn :: (Ord b, Vector v a) => (a -> b) -> v a -> a
    {-# INLINE minimumOn #-}
    minimumOn f = fst . Bundle.foldl1' minBy . Bundle.map (\a -> (a, f a)) . stream
      where
        {-# INLINE minBy #-}
        minBy x y = case compare (snd x) (snd y) of
                      GT -> y
                      _  -> x

    If anyone is willing to implement this and maximumOn for all vector types with docs, tests and at least one benchmark, I would not be opposed to merging such addition.

  2. added a commit that references this issue on Jan 17, 2021
  3. Shimuuar commented on Jan 17, 2021

    @Shimuuar
    Contributor

    Fixed by #356

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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