on 2e4b883 help sign in
1028 lines 33 kB history raw
1-- |
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
7-- Portability : GHC
9module Streamly.Internal.Data.Stream.Transform
10 (
11 -- * Piping
12 -- | Pass through a 'Pipe'.
13 transform
15 -- * Folding
16 , foldrS
18 -- * Mapping
19 -- | Stateless one-to-one maps.
20 , sequence
21 , mapM
23 -- * Mapping Side Effects (Observation)
24 -- | See also the intersperse*_ combinators.
25 , trace
26 , trace_
27 , tap
29 -- * Scanning
30 , scan
31 , scanMany
32 , postscan
33 , smapM
34 , scanlMAfter'
36 -- * Filtering
37 -- | Produce a subset of the stream using criteria based on the values of
38 -- the elements. We can use a concatMap and scan for filtering but these
39 -- combinators are more efficient and convenient.
41 -- mapMaybeM is a general filtering combinator as we can map the stream to
42 -- Just/Nothing using any stateful fold and then use this to filter out.
43 , mapMaybeM
44 , mapMaybe
45 , catMaybes
46 , scanMaybe
48 , with
49 , deleteBy
50 , filter
51 , filterM
53 -- Stateful/scanning filters
54 , uniq
55 , uniqBy
56 , prune
57 , repeated
59 -- * Trimming
60 -- | Produce a subset of the stream trimmed at ends.
62 , take
63 , takeWhile
64 , takeWhileM
65 , takeWhileLast
66 , takeWhileAround
67 , drop
68 , dropLast
69 , dropWhile
70 , dropWhileM
71 , dropWhileLast
72 , dropWhileAround
74 -- * Position Indexing
75 , indexed
76 , indexedR
78 -- * Time Indexing
79 , timestamped
80 , timestampWith
81 , timeIndexed
82 , timeIndexWith
84 -- * Searching
85 , findIndices -- XXX indicesBy
86 , elemIndices -- XXX indicesOf
88 -- * Rolling map
89 -- | Map using the previous element.
90 , rollingMapM
91 , rollingMap
92 , rollingMap2
94 -- Merge
96 -- * Inserting Elements
97 -- | Produce a superset of the stream. This is the opposite of
98 -- filtering/sampling. We can always use concatMap and scan for inserting
99 -- but these combinators are more efficient and convenient.
101 -- Element agnostic (Opposite of sampling)
102 , intersperse
103 , intersperseM -- XXX naming
104 , intersperseBySpan
106 , intersperseSuffix
107 , intersperseSuffixBySpan
109 -- , interspersePrefix
110 -- , interspersePrefixBySpan
112 -- * Inserting Side Effects/Time
113 , intersperseM_ -- XXX naming
114 , delay
115 , intersperseSuffix_
116 , delayPost
117 , interspersePrefix_
118 , delayPre
120 -- * Element Aware Insertion
121 -- | Opposite of filtering
122 , insertBy
123 -- , intersperseByBefore
124 -- , intersperseByAfter
126 -- Fold and Unfold, Buffering
128 -- * Reordering
129 , reverse
130 , reverse'
131 , reassembleBy
133 -- * Either Streams
134 -- Move these to Streamly.Data.Either.Stream?
135 , lefts
136 , rights
137 , both
138 )
139where
141#include "inline.hs"
143import Control.Concurrent (threadDelay)
144import Control.Monad (void)
145import Control.Monad.IO.Class (MonadIO (liftIO))
146import Data.Either (fromLeft, isLeft, isRight, fromRight)
147import Data.Maybe (isJust, fromJust)
149import Streamly.Internal.Data.Fold.Type (Fold)
150import Streamly.Internal.Data.Pipe (Pipe)
151import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64)
153import qualified Streamly.Internal.Data.Fold as FL
154-- import qualified Streamly.Internal.Data.Fold.Window as Window
155import qualified Streamly.Internal.Data.Stream.StreamD.Transform as D
156import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
157import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
160import Streamly.Internal.Data.Stream.Bottom
161import Streamly.Internal.Data.Stream.Type
163import Prelude hiding
164 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
165 , reverse, foldr1 , repeat, scanl, scanl1, zipWith)
167--
168-- $setup
169-- >>> :m
170-- >>> :set -package mtl
171-- >>> import Control.Concurrent (threadDelay)
172-- >>> import Control.Monad.IO.Class (MonadIO (liftIO))
173-- >>> import Control.Monad.Trans (lift)
174-- >>> import Control.Monad.Trans.Identity (runIdentityT)
175-- >>> import Data.Either (fromLeft, fromRight, isLeft, isRight, either)
176-- >>> import Data.Function ((&))
177-- >>> import Data.Maybe (fromJust, isJust)
178-- >>> import Prelude hiding (filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence, reverse, foldr1 , scanl, scanl1)
179-- >>> import Streamly.Internal.Data.Stream as Stream
180-- >>> import qualified Streamly.Data.Fold as Fold
181-- >>> import qualified Streamly.Internal.Data.Fold as Fold
182-- >>> import qualified Streamly.Internal.Data.Fold.Window as Window
183-- >>> import qualified Streamly.Internal.Data.Unfold as Unfold
184-- >>> import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
185--
186-- >>> hSetBuffering stdout LineBuffering
188-- XXX because of the use of D.cons for appending, folds and scans have
189-- quadratic complexity when iterated over a stream. We should use StreamK for
190-- linear performance on iteration.
192------------------------------------------------------------------------------
193-- Piping
194------------------------------------------------------------------------------
196-- | Use a 'Pipe' to transform a stream.
197--
198-- /Pre-release/
199--
200{-# INLINE transform #-}
201transform :: Monad m => Pipe m a b -> Stream m a -> Stream m b
202transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
204------------------------------------------------------------------------------
205-- Transformation Folds
206------------------------------------------------------------------------------
208-- | Right fold to a streaming monad.
209--
210-- > foldrS Stream.cons Stream.nil === id
211--
212-- 'foldrS' can be used to perform stateless stream to stream transformations
213-- like map and filter in general. It can be coupled with a scan to perform
214-- stateful transformations. However, note that the custom map and filter
215-- routines can be much more efficient than this due to better stream fusion.
216--
217-- >>> input = Stream.fromList [1..5]
218-- >>> Stream.fold Fold.toList $ Stream.foldrS Stream.cons Stream.nil input
219-- [1,2,3,4,5]
220--
221-- Find if any element in the stream is 'True':
222--
223-- >>> step x xs = if odd x then return True else xs
224-- >>> input = Stream.fromList (2:4:5:undefined) :: Stream IO Int
225-- >>> Stream.fold Fold.toList $ Stream.foldrS step (return False) input
226-- [True]
227--
228-- Map (+2) on odd elements and filter out the even elements:
229--
230-- >>> step x xs = if odd x then (x + 2) `Stream.cons` xs else xs
231-- >>> input = Stream.fromList [1..5] :: Stream IO Int
232-- >>> Stream.fold Fold.toList $ Stream.foldrS step Stream.nil input
233-- [3,5,7]
234--
235-- /Pre-release/
236{-# INLINE foldrS #-}
237foldrS ::
238 (a -> Stream m b -> Stream m b)
239 -> Stream m b
240 -> Stream m a
241 -> Stream m b
242foldrS f z xs =
243 fromStreamK
244 $ K.foldrS
245 (\y ys -> toStreamK $ f y (fromStreamK ys))
246 (toStreamK z)
247 (toStreamK xs)
249------------------------------------------------------------------------------
250-- Transformation by Mapping
251------------------------------------------------------------------------------
253-- |
254-- >>> mapM f = Stream.sequence . fmap f
255--
256-- Apply a monadic function to each element of the stream and replace it with
257-- the output of the resulting action.
258--
259-- >>> s = Stream.fromList ["a", "b", "c"]
260-- >>> Stream.fold Fold.drain $ Stream.mapM putStr s
261-- abc
262--
263{-# INLINE mapM #-}
264mapM :: Monad m => (a -> m b) -> Stream m a -> Stream m b
265mapM f m = fromStreamK $ D.toStreamK $ D.mapM f $ toStreamD m
267-- |
268-- >>> sequence = Stream.mapM id
269--
270-- Replace the elements of a stream of monadic actions with the outputs of
271-- those actions.
272--
273-- >>> s = Stream.fromList [putStr "a", putStr "b", putStrLn "c"]
274-- >>> Stream.fold Fold.drain $ Stream.sequence s
275-- abc
276--
277{-# INLINE sequence #-}
278sequence :: Monad m => Stream m (m a) -> Stream m a
279sequence = mapM id
281------------------------------------------------------------------------------
282-- Mapping side effects
283------------------------------------------------------------------------------
285-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
286-- add a tap to log the contents flowing through the stream. The fold is used
287-- only for effects, its result is discarded.
288--
289-- @
290-- Fold m a b
291-- |
292-- -----stream m a ---------------stream m a-----
293--
294-- @
295--
296-- >>> s = Stream.enumerateFromTo 1 2
297-- >>> Stream.fold Fold.drain $ Stream.tap (Fold.drainMapM print) s
298-- 1
299-- 2
300--
301-- Compare with 'trace'.
302--
303{-# INLINE tap #-}
304tap :: Monad m => FL.Fold m a b -> Stream m a -> Stream m a
305tap f xs = fromStreamD $ D.tap f (toStreamD xs)
307-- | Apply a monadic function to each element flowing through the stream and
308-- discard the results.
309--
310-- >>> s = Stream.enumerateFromTo 1 2
311-- >>> Stream.fold Fold.drain $ Stream.trace print s
312-- 1
313-- 2
314--
315-- Compare with 'tap'.
316--
317{-# INLINE trace #-}
318trace :: Monad m => (a -> m b) -> Stream m a -> Stream m a
319trace f = mapM (\x -> void (f x) >> return x)
321-- | Perform a side effect before yielding each element of the stream and
322-- discard the results.
323--
324-- >>> s = Stream.enumerateFromTo 1 2
325-- >>> Stream.fold Fold.drain $ Stream.trace_ (print "got here") s
326-- "got here"
327-- "got here"
328--
329-- Same as 'interspersePrefix_' but always serial.
330--
331-- See also: 'trace'
332--
333-- /Pre-release/
334{-# INLINE trace_ #-}
335trace_ :: Monad m => m b -> Stream m a -> Stream m a
336trace_ eff = fromStreamD . D.mapM (\x -> eff >> return x) . toStreamD
338-------------------------------------------------------------------------------
339-- Scanning
340-------------------------------------------------------------------------------
342-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
343-- that it provides an additional @done@ function to be applied on the
344-- accumulator when the stream stops. The result of @done@ is also emitted in
345-- the stream.
346--
347-- This function can be used to allocate a resource in the beginning of the
348-- scan and release it when the stream ends or to flush the internal state of
349-- the scan at the end.
350--
351-- /Pre-release/
352--
353{-# INLINE scanlMAfter' #-}
354scanlMAfter' ::
355 Monad m
356 => (b -> a -> m b)
357 -> m b
358 -> (b -> m b)
359 -> Stream m a
360 -> Stream m b
361scanlMAfter' step initial done stream =
362 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
364------------------------------------------------------------------------------
365-- Scanning with a Fold
366------------------------------------------------------------------------------
368-- XXX It may be useful to have a version of scan where we can keep the
369-- accumulator independent of the value emitted. So that we do not necessarily
370-- have to keep a value in the accumulator which we are not using. We can pass
371-- an extraction function that will take the accumulator and the current value
372-- of the element and emit the next value in the stream. That will also make it
373-- possible to modify the accumulator after using it. In fact, the step function
374-- can return new accumulator and the value to be emitted. The signature would
375-- be more like mapAccumL.
377-- | Strict left scan. Scan a stream using the given monadic fold.
378--
379-- >>> s = Stream.fromList [1..10]
380-- >>> Stream.fold Fold.toList $ Stream.takeWhile (< 10) $ Stream.scan Fold.sum s
381-- [0,1,3,6]
382--
383-- See also: 'usingStateT'
384--
386-- EXPLANATION:
387-- >>> scanl' step z = Stream.scan (Fold.foldl' step z)
388--
389-- Like 'map', 'scanl'' too is a one to one transformation,
390-- however it adds an extra element.
391--
392-- >>> s = Stream.fromList [1,2,3,4]
393-- >>> Stream.fold Fold.toList $ scanl' (+) 0 s
394-- [0,1,3,6,10]
395--
396-- >>> Stream.fold Fold.toList $ scanl' (flip (:)) [] s
397-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
398--
399-- The output of 'scanl'' is the initial value of the accumulator followed by
400-- all the intermediate steps and the final result of 'foldl''.
401--
402-- By streaming the accumulated state after each fold step, we can share the
403-- state across multiple stages of stream composition. Each stage can modify or
404-- extend the state, do some processing with it and emit it for the next stage,
405-- thus modularizing the stream processing. This can be useful in
406-- stateful or event-driven programming.
407--
408-- Consider the following monolithic example, computing the sum and the product
409-- of the elements in a stream in one go using a @foldl'@:
410--
411-- >>> foldl' step z = Stream.fold (Fold.foldl' step z)
412-- >>> foldl' (\(s, p) x -> (s + x, p * x)) (0,1) s
413-- (10,24)
414--
415-- Using @scanl'@ we can make it modular by computing the sum in the first
416-- stage and passing it down to the next stage for computing the product:
417--
418-- >>> :{
419-- foldl' (\(_, p) (s, x) -> (s, p * x)) (0,1)
420-- $ scanl' (\(s, _) x -> (s + x, x)) (0,1)
421-- $ Stream.fromList [1,2,3,4]
422-- :}
423-- (10,24)
424--
425-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
426-- lazy expressions inside the accumulator, it is recommended that a strict
427-- data structure is used for accumulator.
428--
429{-# INLINE scan #-}
430scan :: Monad m => Fold m a b -> Stream m a -> Stream m b
431scan fld m = fromStreamD $ D.scanOnce fld $ toStreamD m
433-- | Like 'scan' but restarts scanning afresh when the scanning fold
434-- terminates.
435--
436{-# INLINE scanMany #-}
437scanMany :: Monad m => Fold m a b -> Stream m a -> Stream m b
438scanMany fld m = fromStreamD $ D.scanMany fld $ toStreamD m
440------------------------------------------------------------------------------
441-- Filtering
442------------------------------------------------------------------------------
444-- | Modify a @Stream m a -> Stream m a@ stream transformation that accepts a
445-- predicate @(a -> b)@ to accept @((s, a) -> b)@ instead, provided a
446-- transformation @Stream m a -> Stream m (s, a)@. Convenient to filter with
447-- index or time.
448--
449-- >>> filterWithIndex = Stream.with Stream.indexed Stream.filter
450--
451-- /Pre-release/
452{-# INLINE with #-}
453with :: Monad m =>
454 (Stream m a -> Stream m (s, a))
455 -> (((s, a) -> b) -> Stream m (s, a) -> Stream m (s, a))
456 -> (((s, a) -> b) -> Stream m a -> Stream m a)
457with f comb g = fmap snd . comb g . f
459-- | Include only those elements that pass a predicate.
460--
461-- >>> filter p = Stream.filterM (return . p)
462-- >>> filter p = Stream.mapMaybe (\x -> if p x then Just x else Nothing)
463-- >>> filter p = Stream.scanMaybe (Fold.filtering p)
464--
465{-# INLINE filter #-}
466filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
467-- filter p = scanMaybe (FL.filtering p)
468filter p m = fromStreamD $ D.filter p $ toStreamD m
470-- | Same as 'filter' but with a monadic predicate.
471--
472-- >>> f p x = p x >>= \r -> return $ if r then Just x else Nothing
473-- >>> filterM p = Stream.mapMaybeM (f p)
474--
475{-# INLINE filterM #-}
476filterM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
477filterM p m = fromStreamD $ D.filterM p $ toStreamD m
479-- | Drop repeated elements that are adjacent to each other using the supplied
480-- comparison function.
481--
482-- >>> uniq = Stream.uniqBy (==)
483--
484-- To strip duplicate path separators:
485--
486-- >>> input = Stream.fromList "//a//b"
487-- >>> f x y = x == '/' && y == '/'
488-- >>> Stream.fold Fold.toList $ Stream.uniqBy f input
489-- "/a/b"
490--
491-- Space: @O(1)@
492--
493-- /Pre-release/
494--
495{-# INLINE uniqBy #-}
496uniqBy :: Monad m =>
497 (a -> a -> Bool) -> Stream m a -> Stream m a
498-- uniqBy eq = scanMaybe (FL.uniqBy eq)
499uniqBy eq = catMaybes . rollingMap f
501 where
503 f pre curr =
504 case pre of
505 Nothing -> Just curr
506 Just x -> if x `eq` curr then Nothing else Just curr
508-- | Drop repeated elements that are adjacent to each other.
509--
510-- >>> uniq = Stream.uniqBy (==)
511--
512{-# INLINE uniq #-}
513uniq :: (Eq a, Monad m) => Stream m a -> Stream m a
514-- uniq = scanMaybe FL.uniq
515uniq = fromStreamD . D.uniq . toStreamD
517-- | Strip all leading and trailing occurrences of an element passing a
518-- predicate and make all other consecutive occurrences uniq.
519--
520-- >> prune p = Stream.dropWhileAround p $ Stream.uniqBy (x y -> p x && p y)
521--
522-- @
523-- > Stream.prune isSpace (Stream.fromList " hello world! ")
524-- "hello world!"
525--
526-- @
527--
528-- Space: @O(1)@
529--
530-- /Unimplemented/
531{-# INLINE prune #-}
532prune ::
533 -- (Monad m, Eq a) =>
534 (a -> Bool) -> Stream m a -> Stream m a
535prune = error "Not implemented yet!"
537-- Possible implementation:
538-- @repeated =
539-- Stream.catMaybes . Stream.parseMany (Parser.groupBy (==) Fold.repeated)@
540--
541-- 'Fold.repeated' should return 'Just' when repeated, and 'Nothing' for a
542-- single element.
544-- | Emit only repeated elements, once.
545--
546-- /Unimplemented/
547repeated :: -- (Monad m, Eq a) =>
548 Stream m a -> Stream m a
549repeated = undefined
551-- | Deletes the first occurrence of the element in the stream that satisfies
552-- the given equality predicate.
553--
554-- >>> input = Stream.fromList [1,3,3,5]
555-- >>> Stream.fold Fold.toList $ Stream.deleteBy (==) 3 input
556-- [1,3,5]
557--
558{-# INLINE deleteBy #-}
559deleteBy :: Monad m => (a -> a -> Bool) -> a -> Stream m a -> Stream m a
560-- deleteBy cmp x = scanMaybe (FL.deleteBy cmp x)
561deleteBy cmp x m = fromStreamD $ D.deleteBy cmp x (toStreamD m)
563------------------------------------------------------------------------------
564-- Trimming
565------------------------------------------------------------------------------
567-- | Same as 'takeWhile' but with a monadic predicate.
568--
569{-# INLINE takeWhileM #-}
570takeWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
571-- takeWhileM p = scanMaybe (FL.takingEndByM_ (\x -> not <$> p x))
572takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
574-- | Take all consecutive elements at the end of the stream for which the
575-- predicate is true.
576--
577-- O(n) space, where n is the number elements taken.
578--
579-- /Unimplemented/
580{-# INLINE takeWhileLast #-}
581takeWhileLast :: -- Monad m =>
582 (a -> Bool) -> Stream m a -> Stream m a
583takeWhileLast = undefined -- fromStreamD $ D.takeWhileLast n $ toStreamD m
585-- | Like 'takeWhile' and 'takeWhileLast' combined.
586--
587-- O(n) space, where n is the number elements taken from the end.
588--
589-- /Unimplemented/
590{-# INLINE takeWhileAround #-}
591takeWhileAround :: -- Monad m =>
592 (a -> Bool) -> Stream m a -> Stream m a
593takeWhileAround = undefined -- fromStreamD $ D.takeWhileAround n $ toStreamD m
595-- | Drop elements in the stream as long as the predicate succeeds and then
596-- take the rest of the stream.
597--
598{-# INLINE dropWhile #-}
599dropWhile :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
600-- dropWhile p = scanMaybe (FL.droppingWhile p)
601dropWhile p m = fromStreamD $ D.dropWhile p $ toStreamD m
603-- | Same as 'dropWhile' but with a monadic predicate.
604--
605{-# INLINE dropWhileM #-}
606dropWhileM :: Monad m => (a -> m Bool) -> Stream m a -> Stream m a
607-- dropWhileM p = scanMaybe (FL.droppingWhileM p)
608dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
610-- | Drop @n@ elements at the end of the stream.
611--
612-- O(n) space, where n is the number elements dropped.
613--
614-- /Unimplemented/
615{-# INLINE dropLast #-}
616dropLast :: -- Monad m =>
617 Int -> Stream m a -> Stream m a
618dropLast = undefined -- fromStreamD $ D.dropLast n $ toStreamD m
620-- | Drop all consecutive elements at the end of the stream for which the
621-- predicate is true.
622--
623-- O(n) space, where n is the number elements dropped.
624--
625-- /Unimplemented/
626{-# INLINE dropWhileLast #-}
627dropWhileLast :: -- Monad m =>
628 (a -> Bool) -> Stream m a -> Stream m a
629dropWhileLast = undefined -- fromStreamD $ D.dropWhileLast n $ toStreamD m
631-- | Like 'dropWhile' and 'dropWhileLast' combined.
632--
633-- O(n) space, where n is the number elements dropped from the end.
634--
635-- /Unimplemented/
636{-# INLINE dropWhileAround #-}
637dropWhileAround :: -- Monad m =>
638 (a -> Bool) -> Stream m a -> Stream m a
639dropWhileAround = undefined -- fromStreamD $ D.dropWhileAround n $ toStreamD m
641------------------------------------------------------------------------------
642-- Inserting Elements
643------------------------------------------------------------------------------
645-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
646-- @stream@ that is less than @elem@ when compared using @cmp@.
647--
648-- >>> insertBy cmp x = Stream.mergeBy cmp (Stream.fromPure x)
649--
650-- >>> input = Stream.fromList [1,3,5]
651-- >>> Stream.fold Fold.toList $ Stream.insertBy compare 2 input
652-- [1,2,3,5]
653--
654{-# INLINE insertBy #-}
655insertBy ::Monad m => (a -> a -> Ordering) -> a -> Stream m a -> Stream m a
656insertBy cmp x m = fromStreamD $ D.insertBy cmp x (toStreamD m)
658-- | Insert a pure value between successive elements of a stream.
659--
660-- >>> input = Stream.fromList "hello"
661-- >>> Stream.fold Fold.toList $ Stream.intersperse ',' input
662-- "h,e,l,l,o"
663--
664{-# INLINE intersperse #-}
665intersperse :: Monad m => a -> Stream m a -> Stream m a
666intersperse a = fromStreamD . D.intersperse a . toStreamD
668-- | Insert a side effect before consuming an element of a stream except the
669-- first one.
670--
671-- >>> input = Stream.fromList "hello"
672-- >>> Stream.fold Fold.drain $ Stream.trace putChar $ Stream.intersperseM_ (putChar '.') input
673-- h.e.l.l.o
674--
675-- /Pre-release/
676{-# INLINE intersperseM_ #-}
677intersperseM_ :: Monad m => m b -> Stream m a -> Stream m a
678intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
680-- | Intersperse a monadic action into the input stream after every @n@
681-- elements.
682--
683-- >> input = Stream.fromList "hello"
684-- >> Stream.fold Fold.toList $ Stream.intersperseBySpan 2 (return ',') input
685-- "he,ll,o"
686--
687-- /Unimplemented/
688{-# INLINE intersperseBySpan #-}
689intersperseBySpan :: -- Monad m =>
690 Int -> m a -> Stream m a -> Stream m a
691intersperseBySpan _n _f _xs = undefined
693-- | Insert an effect and its output after consuming an element of a stream.
694--
695-- >>> input = Stream.fromList "hello"
696-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ intersperseSuffix (putChar '.' >> return ',') input
697-- h.,e.,l.,l.,o.,"h,e,l,l,o,"
698--
699-- /Pre-release/
700{-# INLINE intersperseSuffix #-}
701intersperseSuffix :: Monad m => m a -> Stream m a -> Stream m a
702intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
704-- | Insert a side effect after consuming an element of a stream.
705--
706-- >>> input = Stream.fromList "hello"
707-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffix_ (threadDelay 1000000) input
708-- "hello"
709--
710-- /Pre-release/
711--
712{-# INLINE intersperseSuffix_ #-}
713intersperseSuffix_ :: Monad m => m b -> Stream m a -> Stream m a
714intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
716-- XXX Use an offset argument, like tapOffsetEvery
718-- | Like 'intersperseSuffix' but intersperses an effectful action into the
719-- input stream after every @n@ elements and after the last element.
720--
721-- >>> input = Stream.fromList "hello"
722-- >>> Stream.fold Fold.toList $ Stream.intersperseSuffixBySpan 2 (return ',') input
723-- "he,ll,o,"
724--
725-- /Pre-release/
726--
727{-# INLINE intersperseSuffixBySpan #-}
728intersperseSuffixBySpan :: Monad m
729 => Int -> m a -> Stream m a -> Stream m a
730intersperseSuffixBySpan n eff =
731 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
733-- | Insert a side effect before consuming an element of a stream.
734--
735-- >>> input = Stream.fromList "hello"
736-- >>> Stream.fold Fold.toList $ Stream.trace putChar $ Stream.interspersePrefix_ (putChar '.' >> return ',') input
737-- .h.e.l.l.o"hello"
738--
739-- Same as 'trace_'.
740--
741-- /Pre-release/
742--
743{-# INLINE interspersePrefix_ #-}
744interspersePrefix_ :: Monad m => m b -> Stream m a -> Stream m a
745interspersePrefix_ m = mapM (\x -> void m >> return x)
747------------------------------------------------------------------------------
748-- Inserting Time
749------------------------------------------------------------------------------
751-- | Introduce a delay of specified seconds between elements of the stream.
752--
753-- >>> input = Stream.enumerateFromTo 1 3
754-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delay 1 input
755-- 1
756-- 2
757-- 3
758--
759-- >>> sleep n = liftIO $ threadDelay $ round $ n * 1000000
760-- >>> delay n = Stream.intersperseM_ $ sleep n
761--
762{-# INLINE delay #-}
763delay :: MonadIO m => Double -> Stream m a -> Stream m a
764delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
766-- | Introduce a delay of specified seconds after consuming an element of a
767-- stream.
768--
769-- >>> input = Stream.enumerateFromTo 1 3
770-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delayPost 1 input
771-- 1
772-- 2
773-- 3
774--
775-- /Pre-release/
776--
777{-# INLINE delayPost #-}
778delayPost :: MonadIO m => Double -> Stream m a -> Stream m a
779delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
781-- | Introduce a delay of specified seconds before consuming an element of a
782-- stream.
783--
784-- >>> input = Stream.enumerateFromTo 1 3
785-- >>> Stream.fold (Fold.drainMapM print) $ Stream.delayPre 1 input
786-- 1
787-- 2
788-- 3
789--
790-- /Pre-release/
791--
792{-# INLINE delayPre #-}
793delayPre :: MonadIO m => Double -> Stream m a -> Stream m a
794delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
796------------------------------------------------------------------------------
797-- Reorder in sequence
798------------------------------------------------------------------------------
800-- | Buffer until the next element in sequence arrives. The function argument
801-- determines the difference in sequence numbers. This could be useful in
802-- implementing sequenced streams, for example, TCP reassembly.
803--
804-- /Unimplemented/
805--
806{-# INLINE reassembleBy #-}
807reassembleBy
808 :: -- Monad m =>
809 Fold m a b
810 -> (a -> a -> Int)
811 -> Stream m a
812 -> Stream m b
813reassembleBy = undefined
815------------------------------------------------------------------------------
816-- Position Indexing
817------------------------------------------------------------------------------
819-- |
820-- >>> f = Fold.foldl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
821-- >>> indexed = Stream.postscan f
822-- >>> indexed = Stream.zipWith (,) (Stream.enumerateFrom 0)
823-- >>> indexedR n = fmap (\(i, a) -> (n - i, a)) . indexed
824--
825-- Pair each element in a stream with its index, starting from index 0.
826--
827-- >>> Stream.fold Fold.toList $ Stream.indexed $ Stream.fromList "hello"
828-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
829--
830{-# INLINE indexed #-}
831indexed :: Monad m => Stream m a -> Stream m (Int, a)
832-- indexed = scanMaybe FL.indexing
833indexed = fromStreamD . D.indexed . toStreamD
835-- |
836-- >>> f n = Fold.foldl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
837-- >>> indexedR n = Stream.postscan (f n)
838--
839-- >>> s n = Stream.enumerateFromThen n (n - 1)
840-- >>> indexedR n = Stream.zipWith (,) (s n)
841--
842-- Pair each element in a stream with its index, starting from the
843-- given index @n@ and counting down.
844--
845-- >>> Stream.fold Fold.toList $ Stream.indexedR 10 $ Stream.fromList "hello"
846-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
847--
848{-# INLINE indexedR #-}
849indexedR :: Monad m => Int -> Stream m a -> Stream m (Int, a)
850-- indexedR n = scanMaybe (FL.indexingRev n)
851indexedR n = fromStreamD . D.indexedR n . toStreamD
853-------------------------------------------------------------------------------
854-- Time Indexing
855-------------------------------------------------------------------------------
857-- Note: The timestamp stream must be the second stream in the zip so that the
858-- timestamp is generated after generating the stream element and not before.
859-- If we do not do that then the following example will generate the same
860-- timestamp for first two elements:
861--
862-- Stream.fold Fold.toList $ Stream.timestamped $ Stream.delay $ Stream.enumerateFromTo 1 3
863--
864-- | Pair each element in a stream with an absolute timestamp, using a clock of
865-- specified granularity. The timestamp is generated just before the element
866-- is consumed.
867--
868-- >>> Stream.fold Fold.toList $ Stream.timestampWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
869-- [(AbsTime (TimeSpec {sec = ..., nsec = ...}),1),(AbsTime (TimeSpec {sec = ..., nsec = ...}),2),(AbsTime (TimeSpec {sec = ..., nsec = ...}),3)]
870--
871-- /Pre-release/
872--
873{-# INLINE timestampWith #-}
874timestampWith :: (MonadIO m)
875 => Double -> Stream m a -> Stream m (AbsTime, a)
876timestampWith g stream = zipWith (flip (,)) stream (absTimesWith g)
878-- TBD: check performance vs a custom implementation without using zipWith.
879--
880-- /Pre-release/
881--
882{-# INLINE timestamped #-}
883timestamped :: (MonadIO m)
884 => Stream m a -> Stream m (AbsTime, a)
885timestamped = timestampWith 0.01
887-- | Pair each element in a stream with relative times starting from 0, using a
888-- clock with the specified granularity. The time is measured just before the
889-- element is consumed.
890--
891-- >>> Stream.fold Fold.toList $ Stream.timeIndexWith 0.01 $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
892-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
893--
894-- /Pre-release/Monad
895--
896{-# INLINE timeIndexWith #-}
897timeIndexWith :: (MonadIO m)
898 => Double -> Stream m a -> Stream m (RelTime64, a)
899timeIndexWith g stream = zipWith (flip (,)) stream (relTimesWith g)
901-- | Pair each element in a stream with relative times starting from 0, using a
902-- 10 ms granularity clock. The time is measured just before the element is
903-- consumed.
904--
905-- >>> Stream.fold Fold.toList $ Stream.timeIndexed $ Stream.delay 1 $ Stream.enumerateFromTo 1 3
906-- [(RelTime64 (NanoSecond64 ...),1),(RelTime64 (NanoSecond64 ...),2),(RelTime64 (NanoSecond64 ...),3)]
907--
908-- /Pre-release/
909--
910{-# INLINE timeIndexed #-}
911timeIndexed :: (MonadIO m)
912 => Stream m a -> Stream m (RelTime64, a)
913timeIndexed = timeIndexWith 0.01
915------------------------------------------------------------------------------
916-- Searching
917------------------------------------------------------------------------------
919-- | Find all the indices where the value of the element in the stream is equal
920-- to the given value.
921--
922-- >>> elemIndices a = Stream.findIndices (== a)
923--
924{-# INLINE elemIndices #-}
925elemIndices :: (Monad m, Eq a) => a -> Stream m a -> Stream m Int
926elemIndices a = findIndices (== a)
928------------------------------------------------------------------------------
929-- Rolling map
930------------------------------------------------------------------------------
932-- XXX this is not a one-to-one map so calling it map may not be right.
933-- We can perhaps call it zipWithTail or rollWith.
935-- | Apply a function on every two successive elements of a stream. The first
936-- argument of the map function is the previous element and the second argument
937-- is the current element. When the current element is the first element, the
938-- previous element is 'Nothing'.
939--
940-- /Pre-release/
941--
942{-# INLINE rollingMap #-}
943rollingMap :: Monad m => (Maybe a -> a -> b) -> Stream m a -> Stream m b
944-- rollingMap f = scanMaybe (FL.slide2 $ Window.rollingMap f)
945rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
947-- | Like 'rollingMap' but with an effectful map function.
948--
949-- /Pre-release/
950--
951{-# INLINE rollingMapM #-}
952rollingMapM :: Monad m => (Maybe a -> a -> m b) -> Stream m a -> Stream m b
953-- rollingMapM f = scanMaybe (FL.slide2 $ Window.rollingMapM f)
954rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
956-- | Like 'rollingMap' but requires at least two elements in the stream,
957-- returns an empty stream otherwise.
958--
959-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
960--
961-- /Pre-release/
962--
963{-# INLINE rollingMap2 #-}
964rollingMap2 :: Monad m => (a -> a -> b) -> Stream m a -> Stream m b
965rollingMap2 f m = fromStreamD $ D.rollingMap2 f $ toStreamD m
967------------------------------------------------------------------------------
968-- Maybe Streams
969------------------------------------------------------------------------------
971-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
972-- elements, and return a stream of values extracted from 'Just'.
973--
974-- Equivalent to:
975--
976-- >>> mapMaybe f = Stream.catMaybes . fmap f
977--
978{-# INLINE mapMaybe #-}
979mapMaybe :: Monad m => (a -> Maybe b) -> Stream m a -> Stream m b
980mapMaybe f m = fromStreamD $ D.mapMaybe f $ toStreamD m
982-- | Like 'mapMaybe' but maps a monadic function.
983--
984-- Equivalent to:
985--
986-- >>> mapMaybeM f = Stream.catMaybes . Stream.mapM f
987--
988-- >>> mapM f = Stream.mapMaybeM (\x -> Just <$> f x)
989--
990{-# INLINE_EARLY mapMaybeM #-}
991mapMaybeM :: Monad m
992 => (a -> m (Maybe b)) -> Stream m a -> Stream m b
993mapMaybeM f = fmap fromJust . filter isJust . mapM f
995------------------------------------------------------------------------------
996-- Either streams
997------------------------------------------------------------------------------
999-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1001-- >>> lefts = fmap (fromLeft undefined) . Stream.filter isLeft
1003-- /Pre-release/
1005{-# INLINE lefts #-}
1006lefts :: Monad m => Stream m (Either a b) -> Stream m a
1007lefts = fmap (fromLeft undefined) . filter isLeft
1009-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1011-- >>> rights = fmap (fromRight undefined) . Stream.filter isRight
1013-- /Pre-release/
1015{-# INLINE rights #-}
1016rights :: Monad m => Stream m (Either a b) -> Stream m b
1017rights = fmap (fromRight undefined) . filter isRight
1019-- | Remove the either wrapper and flatten both lefts and as well as rights in
1020-- the output stream.
1022-- >>> both = fmap (either id id)
1024-- /Pre-release/
1026{-# INLINE both #-}
1027both :: Monad m => Stream m (Either a a) -> Stream m a
1028both = fmap (either id id)