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
284mapM :: Monad m => (a -> m b) -> Stream m a -> Stream m b
285mapM f m = fromStreamK $ D.toStreamK $ D.mapM f $ toStreamD m
288-- >>> sequence = Stream.mapM id
290-- Replace the elements of a stream of monadic actions with the outputs of
293-- >>> s = Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
294-- >>> Stream.fold Fold.drain $ Stream.sequence s
298{-# INLINE sequence #-}
299sequence :: Monad m => Stream m (m a) -> Stream m a
302------------------------------------------------------------------------------
303-- Mapping side effects
304------------------------------------------------------------------------------
306-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
307-- add a tap to log the contents flowing through the stream. The fold is used
308-- only for effects, its result is discarded.
313-- -----stream m a ---------------stream m a-----
317-- >>> s = Stream.enumerateFromTo 1 2
318-- >>> Stream.fold Fold.drain $ Stream.tap (Fold.drainBy print) s
322-- Compare with 'trace'.
326tap :: Monad m => FL.Fold m a b -> Stream m a -> Stream m a
327tap f xs = fromStreamD $ D.tap f (toStreamD xs)
329-- | Apply a monadic function to each element flowing through the stream and
330-- discard the results.
332-- >>> s = Stream.enumerateFromTo 1 2
333-- >>> Stream.fold Fold.drain $ Stream.trace print s
337-- Compare with 'tap'.
340trace :: Monad m => (a -> m b) -> Stream m a -> Stream m a
341trace f = mapM (\x -> void (f x) >> return x)
343-- | Perform a side effect before yielding each element of the stream and
344-- discard the results.
346-- >>> s = Stream.enumerateFromTo 1 2
347-- >>> Stream.fold Fold.drain $ Stream.trace_ (print "got here") s
351-- Same as 'interspersePrefix_' but always serial.
357trace_ :: Monad m => m b -> Stream m a -> Stream m a
358trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
360-------------------------------------------------------------------------------
362-------------------------------------------------------------------------------
364-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
365-- that it provides an additional @done@ function to be applied on the
366-- accumulator when the stream stops. The result of @done@ is also emitted in
369-- This function can be used to allocate a resource in the beginning of the
370-- scan and release it when the stream ends or to flush the internal state of
371-- the scan at the end.
375{-# INLINE scanlMAfter' #-}
383scanlMAfter' step initial done stream =
384 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
386------------------------------------------------------------------------------
387-- Scanning with a Fold
388------------------------------------------------------------------------------
390-- XXX It may be useful to have a version of scan where we can keep the
391-- accumulator independent of the value emitted. So that we do not necessarily
392-- have to keep a value in the accumulator which we are not using. We can pass
393-- an extraction function that will take the accumulator and the current value
394-- of the element and emit the next value in the stream. That will also make it
395-- possible to modify the accumulator after using it. In fact, the step function
396-- can return new accumulator and the value to be emitted. The signature would
397-- be more like mapAccumL.
399-- | Strict left scan. Scan a stream using the given monadic fold.
401-- >>> s = Stream.fromList [1..10]
402-- >>> Stream.fold Fold.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum s
405-- See also: 'usingStateT'
410-- >>> scanl' step z = Stream.scan (Fold.foldl' step z)
412-- Like 'map', 'scanl'' too is a one to one transformation,
413-- however it adds an extra element.
415-- >>> s = Stream.fromList [1,2,3,4]
416-- >>> Stream.fold Fold.toList $ scanl' (+) 0 s
419-- >>> Stream.fold Fold.toList $ scanl' (flip (:)) [] s
420-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
422-- The output of 'scanl'' is the initial value of the accumulator followed by
423-- all the intermediate steps and the final result of 'foldl''.
425-- By streaming the accumulated state after each fold step, we can share the
426-- state across multiple stages of stream composition. Each stage can modify or
427-- extend the state, do some processing with it and emit it for the next stage,
428-- thus modularizing the stream processing. This can be useful in
429-- stateful or event-driven programming.
431-- Consider the following monolithic example, computing the sum and the product
432-- of the elements in a stream in one go using a @foldl'@:
434-- >>> foldl' step z = Stream.fold (Fold.foldl' step z)
435-- >>> foldl' (\(s, p) x -> (s + x, p * x)) (0,1) s
438-- Using @scanl'@ we can make it modular by computing the sum in the first
439-- stage and passing it down to the next stage for computing the product:
442-- foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
443-- $ scanl' (\(s, _) x -> (s + x, x)) (0,1)
444-- $ Stream.fromList [1,2,3,4]
448-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
449-- lazy expressions inside the accumulator, it is recommended that a strict
450-- data structure is used for accumulator.
454scan :: Monad m => Fold m a b -> Stream m a -> Stream m b
455scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
457-- | Like 'scan' but restarts scanning afresh when the scanning fold
461{-# INLINE scanMany #-}
462scanMany :: Monad m => Fold m a b -> Stream m a -> Stream m b
463scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
465------------------------------------------------------------------------------
467------------------------------------------------------------------------------
469-- | Modify a @Stream m a -> Stream m a@ stream transformation that accepts a
470-- predicate @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a
471-- transformation @Stream m a -> Stream m (s, a)@. Convenient to filter with
474-- >>> filterWithIndex = Stream.with Stream.indexed Stream.filter
479 (Stream m a -> Stream m (s, a))
480 -> (((s, a) -> b) -> Stream m (s, a) -> Stream m (s, a))
481 -> (((s, a) -> b) -> Stream m a -> Stream m a)
482with f comb g = fmap snd . comb g . f
484-- | Include only those elements that pass a predicate.
486-- >>> filter p = Stream.filterM (return . p)
487-- >>> filter p = Stream.mapMaybe (\x -> if p x then Just x else Nothing)
488-- >>> filter p = Stream.scanMaybe (Fold.filtering p)
492filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
493-- filter p = scanMaybe (FL.filtering p)
494filter p m = fromStreamD $ D.filter p $ toStreamD m
496-- | Same as 'filter' but with a monadic predicate.
498-- >>> f p x = p x >>= \r -> return $ if r then Just x else Nothing
499-- >>> filterM p = Stream.mapMaybeM (f p)
502{-# INLINE filterM #-}
503filterM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
504filterM p m = fromStreamD $ D.filterM p $ toStreamD m
506-- | Drop repeated elements that are adjacent to each other using the supplied
507-- comparison function.
509-- >>> uniq = Stream.uniqBy (==)
511-- To strip duplicate path separators:
513-- >>> input = Stream.fromList "//a//b"
514-- >>> f x y = x == '/' && y == '/'
515-- >>> Stream.fold Fold.toList $ Stream.uniqBy f input
524 (a -> a -> Bool) -> Stream m a -> Stream m a
525-- uniqBy eq = scanMaybe (FL.uniqBy eq)
526uniqBy eq = catMaybes . rollingMap f
533 Just x -> if x `eq` curr then Nothing else Just curr
535-- | Drop repeated elements that are adjacent to each other.
537-- >>> uniq = Stream.uniqBy (==)
541uniq :: (Eq a, Monad m) => Stream m a -> Stream m a
542-- uniq = scanMaybe FL.uniq
543uniq = fromStreamD . D.uniq . toStreamD
545-- | Strip all leading and trailing occurrences of an element passing a
546-- predicate and make all other consecutive occurrences uniq.
548-- >> prune p = Stream.dropWhileAround p $ Stream.uniqBy (x y -> p x && p y)
551-- > Stream.prune isSpace (Stream.fromList " hello world! ")
561 -- (Monad m, Eq a) =>
562 (a -> Bool) -> Stream m a -> Stream m a
563prune = error "Not implemented yet!"
565-- Possible implementation:
567-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
569-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
572-- | Emit only repeated elements, once.
575repeated :: -- (Monad m, Eq a) =>
576 Stream m a -> Stream m a
579-- | Deletes the first occurrence of the element in the stream that satisfies
580-- the given equality predicate.
582-- >>> input = Stream.fromList [1,3,3,5]
583-- >>> Stream.fold Fold.toList $ Stream.deleteBy (==) 3 input
587{-# INLINE deleteBy #-}
588deleteBy :: Monad m => (a -> a -> Bool) -> a -> Stream m a -> Stream m a
589-- deleteBy cmp x = scanMaybe (FL.deleteBy cmp x)
590deleteBy cmp x m = fromStreamD $ D.deleteBy cmp x (toStreamD m)
592------------------------------------------------------------------------------
594------------------------------------------------------------------------------
596-- | Same as 'takeWhile' but with a monadic predicate.
599{-# INLINE takeWhileM #-}
600takeWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
601-- takeWhileM p = scanMaybe (FL.takingEndByM_ (\x -> not <$> p x))
602takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
604-- | Take all consecutive elements at the end of the stream for which the
607-- O(n) space, where n is the number elements taken.
610{-# INLINE takeWhileLast #-}
611takeWhileLast :: -- Monad m =>
612 (a -> Bool) -> Stream m a -> Stream m a
613takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
615-- | Like 'takeWhile' and 'takeWhileLast' combined.
617-- O(n) space, where n is the number elements taken from the end.
620{-# INLINE takeWhileAround #-}
621takeWhileAround :: -- Monad m =>
622 (a -> Bool) -> Stream m a -> Stream m a
623takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
625-- | Drop elements in the stream as long as the predicate succeeds and then
626-- take the rest of the stream.
629{-# INLINE dropWhile #-}
630dropWhile :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
631-- dropWhile p = scanMaybe (FL.droppingWhile p)
632dropWhile p m = fromStreamD $ D.dropWhile p $ toStreamD m
634-- | Same as 'dropWhile' but with a monadic predicate.
637{-# INLINE dropWhileM #-}
638dropWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
639-- dropWhileM p = scanMaybe (FL.droppingWhileM p)
640dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
642-- | Drop @n@ elements at the end of the stream.
644-- O(n) space, where n is the number elements dropped.
647{-# INLINE dropLast #-}
648dropLast :: -- Monad m =>
649 Int -> Stream m a -> Stream m a
650dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
652-- | Drop all consecutive elements at the end of the stream for which the
655-- O(n) space, where n is the number elements dropped.
658{-# INLINE dropWhileLast #-}
659dropWhileLast :: -- Monad m =>
660 (a -> Bool) -> Stream m a -> Stream m a
661dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
663-- | Like 'dropWhile' and 'dropWhileLast' combined.
665-- O(n) space, where n is the number elements dropped from the end.
668{-# INLINE dropWhileAround #-}
669dropWhileAround :: -- Monad m =>
670 (a -> Bool) -> Stream m a -> Stream m a
671dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
673------------------------------------------------------------------------------
675------------------------------------------------------------------------------
677-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
678-- @stream@ that is less than @elem@ when compared using @cmp@.
680-- >>> insertBy cmp x = Stream.mergeBy cmp (Stream.fromPure x)
682-- >>> input = Stream.fromList [1,3,5]
683-- >>> Stream.fold Fold.toList $ Stream.insertBy compare 2 input
687{-# INLINE insertBy #-}
688insertBy ::Monad m => (a -> a -> Ordering) -> a -> Stream m a -> Stream m a
689insertBy cmp x m = fromStreamD $ D.insertBy cmp x (toStreamD m)
691-- | Insert a pure value between successive elements of a stream.
693-- >>> input = Stream.fromList "hello"
694-- >>> Stream.fold Fold.toList $ Stream.intersperse ',' input
698{-# INLINE intersperse #-}
699intersperse :: Monad m => a -> Stream m a -> Stream m a
700intersperse a = fromStreamD . D.intersperse a . toStreamD
702-- | Insert a side effect before consuming an element of a stream except the
705-- >>> input = Stream.fromList "hello"
706-- >>> Stream.fold Fold.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') input
710{-# INLINE intersperseM_ #-}
711intersperseM_ :: Monad m => m b -> Stream m a -> Stream m a
712intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
714-- | Intersperse a monadic action into the input stream after every @n@
717-- >> input = Stream.fromList "hello"
718-- >> Stream.fold Fold.toList $ Stream.intersperseBySpan 2 (return ',') input
722{-# INLINE intersperseBySpan #-}
723intersperseBySpan :: -- Monad m =>
724 Int -> m a -> Stream m a -> Stream m a
725intersperseBySpan _n _f _xs = undefined
727-- | Insert an effect and its output after consuming an element of a stream.
729-- >>> input = Stream.fromList "hello"
730-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') input
731-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
734{-# INLINE intersperseSuffix #-}
735intersperseSuffix :: Monad m => m a -> Stream m a -> Stream m a
736intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
738-- | Insert a side effect after consuming an element of a stream.
740-- >>> input = Stream.fromList "hello"
741-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffix_ (threadDelay 1000000) input
746{-# INLINE intersperseSuffix_ #-}
747intersperseSuffix_ :: Monad m => m b -> Stream m a -> Stream m a
748intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
750-- XXX Use an offset argument, like tapOffsetEvery
752-- | Like 'intersperseSuffix' but intersperses an effectful action into the
753-- input stream after every @n@ elements and after the last element.
755-- >>> input = Stream.fromList "hello"
756-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffixBySpan 2 (return ',') input
761{-# INLINE intersperseSuffixBySpan #-}
762intersperseSuffixBySpan :: Monad m
763 => Int -> m a -> Stream m a -> Stream m a
764intersperseSuffixBySpan n eff =
765 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
767-- | Insert a side effect before consuming an element of a stream.
769-- >>> input = Stream.fromList "hello"
770-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') input
777{-# INLINE interspersePrefix_ #-}
778interspersePrefix_ :: Monad m => m b -> Stream m a -> Stream m a
779interspersePrefix_ m = mapM (\x -> void m >> return x)
781------------------------------------------------------------------------------
783------------------------------------------------------------------------------
785-- | Introduce a delay of specified seconds between elements of the stream.
787-- >>> input = Stream.enumerateFromTo 1 3
788-- >>> Stream.fold (Fold.drainBy print) $ Stream.delay 1 input
793-- >>> sleep n = liftIO $ threadDelay $ round $ n * 1000000
794-- >>> delay n = Stream.intersperseM_ $ sleep n
798delay :: MonadIO m => Double -> Stream m a -> Stream m a
799delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
801-- | Introduce a delay of specified seconds after consuming an element of a
804-- >>> input = Stream.enumerateFromTo 1 3
805-- >>> Stream.fold (Fold.drainBy print) $ Stream.delayPost 1 input
812{-# INLINE delayPost #-}
813delayPost :: MonadIO m => Double -> Stream m a -> Stream m a
814delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
816-- | Introduce a delay of specified seconds before consuming an element of a
819-- >>> input = Stream.enumerateFromTo 1 3
820-- >>> Stream.fold (Fold.drainBy print) $ Stream.delayPre 1 input
827{-# INLINE delayPre #-}
828delayPre :: MonadIO m => Double -> Stream m a -> Stream m a
829delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
831------------------------------------------------------------------------------
832-- Reorder in sequence
833------------------------------------------------------------------------------
835-- | Buffer until the next element in sequence arrives. The function argument
836-- determines the difference in sequence numbers. This could be useful in
837-- implementing sequenced streams, for example, TCP reassembly.
841{-# INLINE reassembleBy #-}
848reassembleBy = undefined
850------------------------------------------------------------------------------
852------------------------------------------------------------------------------
855-- >>> f = Fold.foldl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
856-- >>> indexed = Stream.postscan f
857-- >>> indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
859-- Pair each element in a stream with its index, starting from index 0.
861-- >>> Stream.fold Fold.toList $ Stream.indexed $ Stream.fromList "hello"
862-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
865{-# INLINE indexed #-}
866indexed :: Monad m => Stream m a -> Stream m (Int, a)
867-- indexed = scanMaybe FL.indexing
868indexed = fromStreamD . D.indexed . toStreamD
871-- >>> f n = Fold.foldl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
872-- >>> indexedR n = Stream.postscan (f n)
874-- >>> s n = Stream.enumerateFromThen n (n - 1)
875-- >>> indexedR n = Stream.zipWith (,) (s n)
877-- Pair each element in a stream with its index, starting from the
878-- given index @n@ and counting down.
880-- >>> Stream.fold Fold.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
881-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
884{-# INLINE indexedR #-}
885indexedR :: Monad m => Int -> Stream m a -> Stream m (Int, a)
886-- indexedR n = scanMaybe (FL.indexingRev n)
887indexedR n = fromStreamD . D.indexedR n . toStreamD
889-------------------------------------------------------------------------------
891-------------------------------------------------------------------------------
893-- Note: The timestamp stream must be the second stream in the zip so that the
894-- timestamp is generated after generating the stream element and not before.
895-- If we do not do that then the following example will generate the same
896-- timestamp for first two elements:
898-- Stream.fold Fold.toList $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
900-- | Pair each element in a stream with an absolute timestamp, using a clock of
901-- specified granularity. The timestamp is generated just before the element
904-- >>> Stream.fold Fold.toList $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
905-- [(AbsTime (TimeSpec {sec = ..., nsec = ...}),1),(AbsTime (TimeSpec {sec = ..., nsec = ...}),2),(AbsTime (TimeSpec {sec = ..., nsec = ...}),3)]
909{-# INLINE timestampWith #-}
910timestampWith :: (MonadIO m)
911 => Double -> Stream m a -> Stream m(AbsTime, a)
912timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
914-- TBD: check performance vs a custom implementation without using zipWith.
918{-# INLINE timestamped #-}
919timestamped :: (MonadIO m)
920 => Stream m a -> Stream m(AbsTime, a)
921timestamped = timestampWith 0.01
923-- | Pair each element in a stream with relative times starting from 0, using a
924-- clock with the specified granularity. The time is measured just before the
925-- element is consumed.
927-- >>> Stream.fold Fold.toList $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
928-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
932{-# INLINE timeIndexWith #-}
933timeIndexWith :: (MonadIO m)
934 => Double -> Stream m a -> Stream m(RelTime64, a)
935timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
937-- | Pair each element in a stream with relative times starting from 0, using a
938-- 10 ms granularity clock. The time is measured just before the element is
941-- >>> Stream.fold Fold.toList $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
942-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
946{-# INLINE timeIndexed #-}
947timeIndexed :: (MonadIO m)
948 => Stream m a -> Stream m(RelTime64, a)
949timeIndexed = timeIndexWith 0.01
951------------------------------------------------------------------------------
953------------------------------------------------------------------------------
955-- | Find all the indices where the value of the element in the stream is equal
956-- to the given value.
958-- >>> elemIndices a = Stream.findIndices (== a)
961{-# INLINE elemIndices #-}
962elemIndices :: (Monad m, Eq a) => a -> Stream m a -> Stream m Int
963elemIndices a = findIndices (== a)
965------------------------------------------------------------------------------
967------------------------------------------------------------------------------
969-- XXX this is not a one-to-one map so calling it map may not be right.
970-- We can perhaps call it zipWithTail or rollWith.
972-- | Apply a function on every two successive elements of a stream. The first
973-- argument of the map function is the previous element and the second argument
974-- is the current element. When the current element is the first element, the
975-- previous element is 'Nothing'.
979{-# INLINE rollingMap #-}
980rollingMap :: Monad m => (Maybe a -> a -> b) -> Stream m a -> Stream m b
981-- rollingMap f = scanMaybe (FL.slide2 $ Window.rollingMap f)
982rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
984-- | Like 'rollingMap' but with an effectful map function.
988{-# INLINE rollingMapM #-}
989rollingMapM :: Monad m => (Maybe a -> a -> m b) -> Stream m a -> Stream m b
990-- rollingMapM f = scanMaybe (FL.slide2 $ Window.rollingMapM f)
991rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
993-- | Like 'rollingMap' but requires at least two elements in the stream,
994-- returns an empty stream otherwise.
996-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1000{-# INLINE rollingMap2 #-}
1001rollingMap2 :: Monad m => (a -> a -> b) -> Stream m a -> Stream m b
1002rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
1004------------------------------------------------------------------------------
1006------------------------------------------------------------------------------
1008-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1009-- elements, and return a stream of values extracted from 'Just'.
1013-- >>> mapMaybe f = Stream.catMaybes . fmap f
1016{-# INLINE mapMaybe #-}
1017mapMaybe :: Monad m => (a -> Maybe b) -> Stream m a -> Stream m b
1018mapMaybe f m = fromStreamD $ D.mapMaybe f $ toStreamD m
1020-- | Like 'mapMaybe' but maps a monadic function.
1024-- >>> mapMaybeM f = Stream.catMaybes . Stream.mapM f
1026-- >>> mapM f = Stream.mapMaybeM (\x -> Just <$> f x)
1029{-# INLINE_EARLY mapMaybeM #-}
1031 => (a -> m (Maybe b)) -> Stream m a -> Stream m b
1032mapMaybeM f = fmap fromJust . filter isJust . mapM f
1034------------------------------------------------------------------------------
1036------------------------------------------------------------------------------
1038-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1040-- >>> lefts = fmap (fromLeft undefined) . Stream.filter isLeft
1045lefts :: Monad m => Stream m (Either a b) -> Stream m a
1046lefts = fmap (fromLeft undefined) . filter isLeft
1048-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1050-- >>> rights = fmap (fromRight undefined) . Stream.filter isRight
1054{-# INLINE rights #-}
1055rights :: Monad m => Stream m (Either a b) -> Stream m b
1056rights = fmap (fromRight undefined) . filter isRight
1058-- | Remove the either wrapper and flatten both lefts and as well as rights in
1059-- the output stream.
1061-- >>> both = fmap (either id id)
1066both :: Monad m => Stream m (Either a a) -> Stream m a
1067both = 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