@@ -83,8 +83,9 @@ module Streamly.Internal.Data.Fold
8383 -- $toListRev
8484 , toStream
8585 , toStreamRev
86− , bottomBy
86+ , topBy
8787 , top
88+ , bottomBy
8889 , bottom
8990
9091 -- *** Scanners
@@ -2468,11 +2469,32 @@ bottomBy cmp n = Fold step initial extract
24682469
24692470 extract = return . fst
24702471
2472+-- | Get the top @n@ elements using the supplied comparison function.
2473+--
2474+-- To get bottom n elements instead:
2475+--
2476+-- >>> bottomBy cmp = Fold.topBy (flip cmp)
2477+--
2478+-- Example:
2479+--
2480+-- >>> stream = Stream.fromList [2::Int,7,9,3,1,5,6,11,17]
2481+-- >>> Stream.fold (Fold.topBy compare 3) stream >>= MA.toList
2482+-- [17,11,9]
2483+--
2484+-- /Pre-release/
2485+--
2486+{-# INLINE topBy #-}
2487+topBy :: (MonadIO m, Unbox a) =>
2488+ (a -> a -> Ordering)
2489+ -> Int
2490+ -> Fold m a (MA.Array a)
2491+topBy cmp = bottomBy (flip cmp)
2492+
24712493-- | Fold the input stream to top n elements.
24722494--
24732495-- Definition:
24742496--
2475−-- >>> top = Fold.bottomBy $ flip compare
2497+-- >>> top = Fold.topBy compare
24762498--
24772499-- >>> stream = Stream.fromList [2::Int,7,9,3,1,5,6,11,17]
24782500-- >>> Stream.fold (Fold.top 3) stream >>= MA.toList