module StreamingHelp 
    ( minStreamOn
    , sortStreamOn
    , module Streaming
    , module StreamingHelp.Data
    ) where
import Streaming
import StreamingHelp.Data
import qualified Streaming.Prelude as S
import qualified Control.Foldl as L
import Data.Function (on)


minStreamOn :: Ord a => (b -> a) -> StreamOf b -> Maybe b
{-# INLINE minStreamOn #-}
minStreamOn f = runIdentity
    . L.purely S.fold_ (L.minimumBy (compare `on` f))

-- this hopefully also nub the stream in most cases
--orderStreamOn :: Ord b => (a -> b) -> Stream (Of a) Identity () -> Identity (Of (M.Map b a) ())
sortStreamOn :: Ord a => (b -> a) -> StreamOf b -> Stream (Of b) Identity ()
{-# INLINE sortStreamOn #-}
sortStreamOn f = S.each . runIdentity . L.purely S.fold_ L.map . S.map g
  where
    g x = (f x,x)
