2-- Module : Streamly.Internal.Data.Stream.Transform
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
9module Streamly.Internal.Data.Stream.Transform
12 -- | Pass through a 'Pipe'.
20 -- | Stateless one-to-one maps.
24 -- * Mapping Side Effects (Observation)
25 -- | See also the intersperse*_ combinators.
38 -- | Produce a subset of the stream using criteria based on the values of
39 -- the elements. We can use a concatMap and scan for filtering but these
40 -- combinators are more efficient and convenient.
42 -- mapMaybeM is a general filtering combinator as we can map the stream to
43 -- Just/Nothing using any stateful fold and then use this to filter out.
54 -- Stateful/scanning filters
61 -- | Produce a subset of the stream trimmed at ends.
75 -- * Position Indexing
86 , findIndices -- XXX indicesBy
87 , elemIndices -- XXX indicesOf
90 -- | Map using the previous element.
97 -- * Inserting Elements
98 -- | Produce a superset of the stream. This is the opposite of
99 -- filtering/sampling. We can always use concatMap and scan for inserting
100 -- but these combinators are more efficient and convenient.
102 -- Element agnostic (Opposite of sampling)
104 , intersperseM -- XXX naming
108 , intersperseSuffixBySpan
110 -- , interspersePrefix
111 -- , interspersePrefixBySpan
113 -- * Inserting Side Effects/Time
114 , intersperseM_ -- XXX naming
121 -- * Element Aware Insertion
122 -- | Opposite of filtering
124 -- , intersperseByBefore
125 -- , intersperseByAfter
127 -- Fold and Unfold, Buffering
135 -- Move these to Streamly.Data.Either.Stream?
144import Control.Concurrent (threadDelay)
145import Control.Monad (void)
146import Control.Monad.IO.Class (MonadIO (liftIO))
147import Control.Monad.Trans.Class (MonadTrans(..))
148import Data.Either (fromLeft, isLeft, isRight, fromRight)
149import Data.Maybe (isJust, fromJust)
151import Streamly.Internal.Data.Fold.Type (Fold)
152import Streamly.Internal.Data.Pipe (Pipe)
153import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64)
155import qualified Streamly.Internal.Data.Fold as FL
156-- import qualified Streamly.Internal.Data.Fold.Window as Window
157import qualified Streamly.Internal.Data.Stream.StreamD.Transform as D
158import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
159import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
162import Streamly.Internal.Data.Stream.Bottom
163import Streamly.Internal.Data.Stream.Type
166 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
167 , reverse, foldr1 , repeat, scanl, scanl1, zipWith)
172-- >>> import Control.Concurrent (threadDelay)
173-- >>> import Control.Monad.IO.Class (MonadIO (liftIO))
174-- >>> import Control.Monad.Trans (lift)
175-- >>> import Control.Monad.Trans.Identity (runIdentityT)
176-- >>> import Data.Either (fromLeft, fromRight, isLeft, isRight, either)
177-- >>> import Data.Function ((&))
178-- >>> import Data.Maybe (fromJust, isJust)
179-- >>> import Prelude hiding (filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
180-- >>> import Streamly.Internal.Data.Stream as Stream
181-- >>> import qualified Streamly.Data.Fold as Fold
182-- >>> import qualified Streamly.Internal.Data.Fold as Fold
183-- >>> import qualified Streamly.Internal.Data.Fold.Window as Window
184-- >>> import qualified Streamly.Internal.Data.Unfold as Unfold
185-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
187-- >>> hSetBuffering stdout LineBuffering
189-- XXX because of the use of D.cons for appending, folds and scans have
190-- quadratic complexity when iterated over a stream. We should use StreamK for
191-- linear performance on iteration.
193------------------------------------------------------------------------------
195------------------------------------------------------------------------------
197-- | Use a 'Pipe' to transform a stream.
201{-# INLINE transform #-}
202transform :: Monad m => Pipe m a b -> Stream m a -> Stream m b
203transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
205------------------------------------------------------------------------------
206-- Transformation Folds
207------------------------------------------------------------------------------
209-- | Right fold to a streaming monad.
211-- > foldrS Stream.cons Stream.nil === id
213-- 'foldrS' can be used to perform stateless stream to stream transformations
214-- like map and filter in general. It can be coupled with a scan to perform
215-- stateful transformations. However, note that the custom map and filter
216-- routines can be much more efficient than this due to better stream fusion.
218-- >>> input = Stream.fromList [1..5]
219-- >>> Stream.fold Fold.toList $ Stream.foldrS Stream.cons Stream.nil input
222-- Find if any element in the stream is 'True':
224-- >>> step x xs = if odd x then return True else xs
225-- >>> input = Stream.fromList (2:4:5:undefined) :: Stream IO Int
226-- >>> Stream.fold Fold.toList $ Stream.foldrS step (return False) input
229-- Map (+2) on odd elements and filter out the even elements:
231-- >>> step x xs = if odd x then (x + 2) `Stream.cons` xs else xs
232-- >>> input = Stream.fromList [1..5] :: Stream IO Int
233-- >>> Stream.fold Fold.toList $ Stream.foldrS step Stream.nil input
239 (a -> Stream m b -> Stream m b)
246 (\y ys -> toStreamK $ f y (fromStreamK ys))
250-- | Right fold to a transformer monad. This is the most general right fold
251-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
252-- implementation can be more efficient:
254-- >>> foldrS = foldrT
256-- >>> step f x xs = lift $ f x (runIdentityT xs)
257-- >>> foldrM f z s = runIdentityT $ foldrT (step f) (lift z) s
259-- 'foldrT' can be used to translate streamly streams to other transformer
260-- monads e.g. to a different streaming type.
264foldrT :: (Monad m, Monad (s m), MonadTrans s)
265 => (a -> s m b -> s m b) -> s m b -> Stream m a -> s m b
266foldrT f z s = D.foldrT f z (toStreamD s)
268------------------------------------------------------------------------------
269-- Transformation by Mapping
270------------------------------------------------------------------------------
273-- >>> mapM f = Stream.sequence . fmap f
275-- Apply a monadic function to each element of the stream and replace it with
276-- the output of the resulting action.
278-- >>> s = Stream.fromList ["a", "b", "c"]
279-- >>> Stream.fold Fold.drain $ Stream.mapM putStr s
283mapM :: Monad m => (a -> m b) -> Stream m a -> Stream m b
284mapM f m = fromStreamK $ D.toStreamK $ D.mapM f $ toStreamD m
287-- >>> sequence = Stream.mapM id
289-- Replace the elements of a stream of monadic actions with the outputs of
292-- >>> s = Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
293-- >>> Stream.fold Fold.drain $ Stream.sequence s
296{-# INLINE sequence #-}
297sequence :: Monad m => Stream m (m a) -> Stream m a
300------------------------------------------------------------------------------
301-- Mapping side effects
302------------------------------------------------------------------------------
304-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
305-- add a tap to log the contents flowing through the stream. The fold is used
306-- only for effects, its result is discarded.
311-- -----stream m a ---------------stream m a-----
315-- >>> s = Stream.enumerateFromTo 1 2
316-- >>> Stream.fold Fold.drain $ Stream.tap (Fold.drainBy print) s
320-- Compare with 'trace'.
323tap :: Monad m => FL.Fold m a b -> Stream m a -> Stream m a
324tap f xs = fromStreamD $ D.tap f (toStreamD xs)
326-- | Apply a monadic function to each element flowing through the stream and
327-- discard the results.
329-- >>> s = Stream.enumerateFromTo 1 2
330-- >>> Stream.fold Fold.drain $ Stream.trace print s
334-- Compare with 'tap'.
337trace :: Monad m => (a -> m b) -> Stream m a -> Stream m a
338trace f = mapM (\x -> void (f x) >> return x)
340-- | Perform a side effect before yielding each element of the stream and
341-- discard the results.
343-- >>> s = Stream.enumerateFromTo 1 2
344-- >>> Stream.fold Fold.drain $ Stream.trace_ (print "got here") s
348-- Same as 'interspersePrefix_' but always serial.
354trace_ :: Monad m => m b -> Stream m a -> Stream m a
355trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
357-------------------------------------------------------------------------------
359-------------------------------------------------------------------------------
361-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
362-- that it provides an additional @done@ function to be applied on the
363-- accumulator when the stream stops. The result of @done@ is also emitted in
366-- This function can be used to allocate a resource in the beginning of the
367-- scan and release it when the stream ends or to flush the internal state of
368-- the scan at the end.
372{-# INLINE scanlMAfter' #-}
380scanlMAfter' step initial done stream =
381 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
383------------------------------------------------------------------------------
384-- Scanning with a Fold
385------------------------------------------------------------------------------
387-- XXX It may be useful to have a version of scan where we can keep the
388-- accumulator independent of the value emitted. So that we do not necessarily
389-- have to keep a value in the accumulator which we are not using. We can pass
390-- an extraction function that will take the accumulator and the current value
391-- of the element and emit the next value in the stream. That will also make it
392-- possible to modify the accumulator after using it. In fact, the step function
393-- can return new accumulator and the value to be emitted. The signature would
394-- be more like mapAccumL.
396-- | Strict left scan. Scan a stream using the given monadic fold.
398-- >>> s = Stream.fromList [1..10]
399-- >>> Stream.fold Fold.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum s
402-- See also: 'usingStateT'
406-- >>> scanl' step z = Stream.scan (Fold.foldl' step z)
408-- Like 'map', 'scanl'' too is a one to one transformation,
409-- however it adds an extra element.
411-- >>> s = Stream.fromList [1,2,3,4]
412-- >>> Stream.fold Fold.toList $ scanl' (+) 0 s
415-- >>> Stream.fold Fold.toList $ scanl' (flip (:)) [] s
416-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
418-- The output of 'scanl'' is the initial value of the accumulator followed by
419-- all the intermediate steps and the final result of 'foldl''.
421-- By streaming the accumulated state after each fold step, we can share the
422-- state across multiple stages of stream composition. Each stage can modify or
423-- extend the state, do some processing with it and emit it for the next stage,
424-- thus modularizing the stream processing. This can be useful in
425-- stateful or event-driven programming.
427-- Consider the following monolithic example, computing the sum and the product
428-- of the elements in a stream in one go using a @foldl'@:
430-- >>> foldl' step z = Stream.fold (Fold.foldl' step z)
431-- >>> foldl' (\(s, p) x -> (s + x, p * x)) (0,1) s
434-- Using @scanl'@ we can make it modular by computing the sum in the first
435-- stage and passing it down to the next stage for computing the product:
438-- foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
439-- $ scanl' (\(s, _) x -> (s + x, x)) (0,1)
440-- $ Stream.fromList [1,2,3,4]
444-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
445-- lazy expressions inside the accumulator, it is recommended that a strict
446-- data structure is used for accumulator.
449scan :: Monad m => Fold m a b -> Stream m a -> Stream m b
450scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
452-- | Like 'scan' but restarts scanning afresh when the scanning fold
455{-# INLINE scanMany #-}
456scanMany :: Monad m => Fold m a b -> Stream m a -> Stream m b
457scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
459------------------------------------------------------------------------------
461------------------------------------------------------------------------------
463-- | Modify a @Stream m a -> Stream m a@ stream transformation that accepts a
464-- predicate @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a
465-- transformation @Stream m a -> Stream m (s, a)@. Convenient to filter with
468-- >>> filterWithIndex = Stream.with Stream.indexed Stream.filter
473 (Stream m a -> Stream m (s, a))
474 -> (((s, a) -> b) -> Stream m (s, a) -> Stream m (s, a))
475 -> (((s, a) -> b) -> Stream m a -> Stream m a)
476with f comb g = fmap snd . comb g . f
478-- | Include only those elements that pass a predicate.
480-- >>> filter p = Stream.filterM (return . p)
481-- >>> filter p = Stream.mapMaybe (\x -> if p x then Just x else Nothing)
482-- >>> filter p = Stream.scanMaybe (Fold.filtering p)
485filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
486-- filter p = scanMaybe (FL.filtering p)
487filter p m = fromStreamD $ D.filter p $ toStreamD m
489-- | Same as 'filter' but with a monadic predicate.
491-- >>> f p x = p x >>= \r -> return $ if r then Just x else Nothing
492-- >>> filterM p = Stream.mapMaybeM (f p)
494{-# INLINE filterM #-}
495filterM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
496filterM p m = fromStreamD $ D.filterM p $ toStreamD m
498-- | Drop repeated elements that are adjacent to each other using the supplied
499-- comparison function.
501-- >>> uniq = Stream.uniqBy (==)
503-- To strip duplicate path separators:
505-- >>> input = Stream.fromList "//a//b"
506-- >>> f x y = x == '/' && y == '/'
507-- >>> Stream.fold Fold.toList $ Stream.uniqBy f input
516 (a -> a -> Bool) -> Stream m a -> Stream m a
517-- uniqBy eq = scanMaybe (FL.uniqBy eq)
518uniqBy eq = catMaybes . rollingMap f
525 Just x -> if x `eq` curr then Nothing else Just curr
527-- | Drop repeated elements that are adjacent to each other.
529-- >>> uniq = Stream.uniqBy (==)
532uniq :: (Eq a, Monad m) => Stream m a -> Stream m a
533-- uniq = scanMaybe FL.uniq
534uniq = fromStreamD . D.uniq . toStreamD
536-- | Strip all leading and trailing occurrences of an element passing a
537-- predicate and make all other consecutive occurrences uniq.
539-- >> prune p = Stream.dropWhileAround p $ Stream.uniqBy (x y -> p x && p y)
542-- > Stream.prune isSpace (Stream.fromList " hello world! ")
552 -- (Monad m, Eq a) =>
553 (a -> Bool) -> Stream m a -> Stream m a
554prune = error "Not implemented yet!"
556-- Possible implementation:
558-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
560-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
563-- | Emit only repeated elements, once.
566repeated :: -- (Monad m, Eq a) =>
567 Stream m a -> Stream m a
570-- | Deletes the first occurrence of the element in the stream that satisfies
571-- the given equality predicate.
573-- >>> input = Stream.fromList [1,3,3,5]
574-- >>> Stream.fold Fold.toList $ Stream.deleteBy (==) 3 input
577{-# INLINE deleteBy #-}
578deleteBy :: Monad m => (a -> a -> Bool) -> a -> Stream m a -> Stream m a
579-- deleteBy cmp x = scanMaybe (FL.deleteBy cmp x)
580deleteBy cmp x m = fromStreamD $ D.deleteBy cmp x (toStreamD m)
582------------------------------------------------------------------------------
584------------------------------------------------------------------------------
586-- | Same as 'takeWhile' but with a monadic predicate.
588{-# INLINE takeWhileM #-}
589takeWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
590-- takeWhileM p = scanMaybe (FL.takingEndByM_ (\x -> not <$> p x))
591takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
593-- | Take all consecutive elements at the end of the stream for which the
596-- O(n) space, where n is the number elements taken.
599{-# INLINE takeWhileLast #-}
600takeWhileLast :: -- Monad m =>
601 (a -> Bool) -> Stream m a -> Stream m a
602takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
604-- | Like 'takeWhile' and 'takeWhileLast' combined.
606-- O(n) space, where n is the number elements taken from the end.
609{-# INLINE takeWhileAround #-}
610takeWhileAround :: -- Monad m =>
611 (a -> Bool) -> Stream m a -> Stream m a
612takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
614-- | Drop elements in the stream as long as the predicate succeeds and then
615-- take the rest of the stream.
617{-# INLINE dropWhile #-}
618dropWhile :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
619-- dropWhile p = scanMaybe (FL.droppingWhile p)
620dropWhile p m = fromStreamD $ D.dropWhile p $ toStreamD m
622-- | Same as 'dropWhile' but with a monadic predicate.
624{-# INLINE dropWhileM #-}
625dropWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
626-- dropWhileM p = scanMaybe (FL.droppingWhileM p)
627dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
629-- | Drop @n@ elements at the end of the stream.
631-- O(n) space, where n is the number elements dropped.
634{-# INLINE dropLast #-}
635dropLast :: -- Monad m =>
636 Int -> Stream m a -> Stream m a
637dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
639-- | Drop all consecutive elements at the end of the stream for which the
642-- O(n) space, where n is the number elements dropped.
645{-# INLINE dropWhileLast #-}
646dropWhileLast :: -- Monad m =>
647 (a -> Bool) -> Stream m a -> Stream m a
648dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
650-- | Like 'dropWhile' and 'dropWhileLast' combined.
652-- O(n) space, where n is the number elements dropped from the end.
655{-# INLINE dropWhileAround #-}
656dropWhileAround :: -- Monad m =>
657 (a -> Bool) -> Stream m a -> Stream m a
658dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
660------------------------------------------------------------------------------
662------------------------------------------------------------------------------
664-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
665-- @stream@ that is less than @elem@ when compared using @cmp@.
667-- >>> insertBy cmp x = Stream.mergeBy cmp (Stream.fromPure x)
669-- >>> input = Stream.fromList [1,3,5]
670-- >>> Stream.fold Fold.toList $ Stream.insertBy compare 2 input
673{-# INLINE insertBy #-}
674insertBy ::Monad m => (a -> a -> Ordering) -> a -> Stream m a -> Stream m a
675insertBy cmp x m = fromStreamD $ D.insertBy cmp x (toStreamD m)
677-- | Insert a pure value between successive elements of a stream.
679-- >>> input = Stream.fromList "hello"
680-- >>> Stream.fold Fold.toList $ Stream.intersperse ',' input
683{-# INLINE intersperse #-}
684intersperse :: Monad m => a -> Stream m a -> Stream m a
685intersperse a = fromStreamD . D.intersperse a . toStreamD
687-- | Insert a side effect before consuming an element of a stream except the
690-- >>> input = Stream.fromList "hello"
691-- >>> Stream.fold Fold.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') input
695{-# INLINE intersperseM_ #-}
696intersperseM_ :: Monad m => m b -> Stream m a -> Stream m a
697intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
699-- | Intersperse a monadic action into the input stream after every @n@
702-- >> input = Stream.fromList "hello"
703-- >> Stream.fold Fold.toList $ Stream.intersperseBySpan 2 (return ',') input
707{-# INLINE intersperseBySpan #-}
708intersperseBySpan :: -- Monad m =>
709 Int -> m a -> Stream m a -> Stream m a
710intersperseBySpan _n _f _xs = undefined
712-- | Insert an effect and its output after consuming an element of a stream.
714-- >>> input = Stream.fromList "hello"
715-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') input
716-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
719{-# INLINE intersperseSuffix #-}
720intersperseSuffix :: Monad m => m a -> Stream m a -> Stream m a
721intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
723-- | Insert a side effect after consuming an element of a stream.
725-- >>> input = Stream.fromList "hello"
726-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffix_ (threadDelay 1000000) input
731{-# INLINE intersperseSuffix_ #-}
732intersperseSuffix_ :: Monad m => m b -> Stream m a -> Stream m a
733intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
735-- XXX Use an offset argument, like tapOffsetEvery
737-- | Like 'intersperseSuffix' but intersperses an effectful action into the
738-- input stream after every @n@ elements and after the last element.
740-- >>> input = Stream.fromList "hello"
741-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffixBySpan 2 (return ',') input
746{-# INLINE intersperseSuffixBySpan #-}
747intersperseSuffixBySpan :: Monad m
748 => Int -> m a -> Stream m a -> Stream m a
749intersperseSuffixBySpan n eff =
750 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
752-- | Insert a side effect before consuming an element of a stream.
754-- >>> input = Stream.fromList "hello"
755-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') input
762{-# INLINE interspersePrefix_ #-}
763interspersePrefix_ :: Monad m => m b -> Stream m a -> Stream m a
764interspersePrefix_ m = mapM (\x -> void m >> return x)
766------------------------------------------------------------------------------
768------------------------------------------------------------------------------
770-- | Introduce a delay of specified seconds between elements of the stream.
772-- >>> input = Stream.enumerateFromTo 1 3
773-- >>> Stream.fold (Fold.drainBy print) $ Stream.delay 1 input
778-- >>> sleep n = liftIO $ threadDelay $ round $ n * 1000000
779-- >>> delay n = Stream.intersperseM_ $ sleep n
782delay :: MonadIO m => Double -> Stream m a -> Stream m a
783delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
785-- | Introduce a delay of specified seconds after consuming an element of a
788-- >>> input = Stream.enumerateFromTo 1 3
789-- >>> Stream.fold (Fold.drainBy print) $ Stream.delayPost 1 input
796{-# INLINE delayPost #-}
797delayPost :: MonadIO m => Double -> Stream m a -> Stream m a
798delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
800-- | Introduce a delay of specified seconds before consuming an element of a
803-- >>> input = Stream.enumerateFromTo 1 3
804-- >>> Stream.fold (Fold.drainBy print) $ Stream.delayPre 1 input
811{-# INLINE delayPre #-}
812delayPre :: MonadIO m => Double -> Stream m a -> Stream m a
813delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
815------------------------------------------------------------------------------
816-- Reorder in sequence
817------------------------------------------------------------------------------
819-- | Buffer until the next element in sequence arrives. The function argument
820-- determines the difference in sequence numbers. This could be useful in
821-- implementing sequenced streams, for example, TCP reassembly.
825{-# INLINE reassembleBy #-}
832reassembleBy = undefined
834------------------------------------------------------------------------------
836------------------------------------------------------------------------------
839-- >>> f = Fold.foldl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
840-- >>> indexed = Stream.postscan f
841-- >>> indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
843-- Pair each element in a stream with its index, starting from index 0.
845-- >>> Stream.fold Fold.toList $ Stream.indexed $ Stream.fromList "hello"
846-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
848{-# INLINE indexed #-}
849indexed :: Monad m => Stream m a -> Stream m (Int, a)
850-- indexed = scanMaybe FL.indexing
851indexed = fromStreamD . D.indexed . toStreamD
854-- >>> f n = Fold.foldl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
855-- >>> indexedR n = Stream.postscan (f n)
857-- >>> s n = Stream.enumerateFromThen n (n - 1)
858-- >>> indexedR n = Stream.zipWith (,) (s n)
860-- Pair each element in a stream with its index, starting from the
861-- given index @n@ and counting down.
863-- >>> Stream.fold Fold.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
864-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
866{-# INLINE indexedR #-}
867indexedR :: Monad m => Int -> Stream m a -> Stream m (Int, a)
868-- indexedR n = scanMaybe (FL.indexingRev n)
869indexedR n = fromStreamD . D.indexedR n . toStreamD
871-------------------------------------------------------------------------------
873-------------------------------------------------------------------------------
875-- Note: The timestamp stream must be the second stream in the zip so that the
876-- timestamp is generated after generating the stream element and not before.
877-- If we do not do that then the following example will generate the same
878-- timestamp for first two elements:
880-- Stream.fold Fold.toList $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
882-- | Pair each element in a stream with an absolute timestamp, using a clock of
883-- specified granularity. The timestamp is generated just before the element
886-- >>> Stream.fold Fold.toList $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
887-- [(AbsTime (TimeSpec {sec = ..., nsec = ...}),1),(AbsTime (TimeSpec {sec = ..., nsec = ...}),2),(AbsTime (TimeSpec {sec = ..., nsec = ...}),3)]
891{-# INLINE timestampWith #-}
892timestampWith :: (MonadIO m)
893 => Double -> Stream m a -> Stream m(AbsTime, a)
894timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
896-- TBD: check performance vs a custom implementation without using zipWith.
900{-# INLINE timestamped #-}
901timestamped :: (MonadIO m)
902 => Stream m a -> Stream m(AbsTime, a)
903timestamped = timestampWith 0.01
905-- | Pair each element in a stream with relative times starting from 0, using a
906-- clock with the specified granularity. The time is measured just before the
907-- element is consumed.
909-- >>> Stream.fold Fold.toList $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
910-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
914{-# INLINE timeIndexWith #-}
915timeIndexWith :: (MonadIO m)
916 => Double -> Stream m a -> Stream m(RelTime64, a)
917timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
919-- | Pair each element in a stream with relative times starting from 0, using a
920-- 10 ms granularity clock. The time is measured just before the element is
923-- >>> Stream.fold Fold.toList $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
924-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
928{-# INLINE timeIndexed #-}
929timeIndexed :: (MonadIO m)
930 => Stream m a -> Stream m(RelTime64, a)
931timeIndexed = timeIndexWith 0.01
933------------------------------------------------------------------------------
935------------------------------------------------------------------------------
937-- | Find all the indices where the value of the element in the stream is equal
938-- to the given value.
940-- >>> elemIndices a = Stream.findIndices (== a)
942{-# INLINE elemIndices #-}
943elemIndices :: (Monad m, Eq a) => a -> Stream m a -> Stream m Int
944elemIndices a = findIndices (== a)
946------------------------------------------------------------------------------
948------------------------------------------------------------------------------
950-- XXX this is not a one-to-one map so calling it map may not be right.
951-- We can perhaps call it zipWithTail or rollWith.
953-- | Apply a function on every two successive elements of a stream. The first
954-- argument of the map function is the previous element and the second argument
955-- is the current element. When the current element is the first element, the
956-- previous element is 'Nothing'.
960{-# INLINE rollingMap #-}
961rollingMap :: Monad m => (Maybe a -> a -> b) -> Stream m a -> Stream m b
962-- rollingMap f = scanMaybe (FL.slide2 $ Window.rollingMap f)
963rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
965-- | Like 'rollingMap' but with an effectful map function.
969{-# INLINE rollingMapM #-}
970rollingMapM :: Monad m => (Maybe a -> a -> m b) -> Stream m a -> Stream m b
971-- rollingMapM f = scanMaybe (FL.slide2 $ Window.rollingMapM f)
972rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
974-- | Like 'rollingMap' but requires at least two elements in the stream,
975-- returns an empty stream otherwise.
977-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
981{-# INLINE rollingMap2 #-}
982rollingMap2 :: Monad m => (a -> a -> b) -> Stream m a -> Stream m b
983rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
985------------------------------------------------------------------------------
987------------------------------------------------------------------------------
989-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
990-- elements, and return a stream of values extracted from 'Just'.
994-- >>> mapMaybe f = Stream.catMaybes . fmap f
996{-# INLINE mapMaybe #-}
997mapMaybe :: Monad m => (a -> Maybe b) -> Stream m a -> Stream m b
998mapMaybe f m = fromStreamD $ D.mapMaybe f $ toStreamD m
1000-- | Like 'mapMaybe' but maps a monadic function.
1004-- >>> mapMaybeM f = Stream.catMaybes . Stream.mapM f
1006-- >>> mapM f = Stream.mapMaybeM (\x -> Just <$> f x)
1008{-# INLINE_EARLY mapMaybeM #-}
1010 => (a -> m (Maybe b)) -> Stream m a -> Stream m b
1011mapMaybeM f = fmap fromJust . filter isJust . mapM f
1013------------------------------------------------------------------------------
1015------------------------------------------------------------------------------
1017-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1019-- >>> lefts = fmap (fromLeft undefined) . Stream.filter isLeft
1024lefts :: Monad m => Stream m (Either a b) -> Stream m a
1025lefts = fmap (fromLeft undefined) . filter isLeft
1027-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1029-- >>> rights = fmap (fromRight undefined) . Stream.filter isRight
1033{-# INLINE rights #-}
1034rights :: Monad m => Stream m (Either a b) -> Stream m b
1035rights = fmap (fromRight undefined) . filter isRight
1037-- | Remove the either wrapper and flatten both lefts and as well as rights in
1038-- the output stream.
1040-- >>> both = fmap (either id id)
1045both :: Monad m => Stream m (Either a a) -> Stream m a
1046both = fmap (either id id)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list