on da62ada help sign in
1268 lines 39 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Stream.IsStream.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.IsStream.Transform
10 (
11 -- * Piping
12 -- | Pass through a 'Pipe'.
13 transform
15 -- * Folding
16 , foldrS
17 , foldrT
19 -- * Mapping
20 -- | Stateless one-to-one maps.
21 , Serial.map
22 , sequence
23 , mapM
24 , smapM
26 -- * Mapping Side Effects
27 , trace
28 , trace_
29 , tap
30 , tapOffsetEvery
31 , tapAsync
32 , tapRate
33 , pollCounts
35 -- * Scanning By 'Fold'
36 , scan
37 , postscan
39 -- * Scanning
40 -- | Left scans. Stateful, mostly one-to-one maps.
41 , scanl'
42 , scanlM'
43 , scanlMAfter'
44 , postscanl'
45 , postscanlM'
46 , prescanl'
47 , prescanlM'
48 , scanl1'
49 , scanl1M'
51 -- XXX Once we have pipes the contravariant transformations can be
52 -- represented by attaching pipes before a transformation.
53 --
54 -- , lscanl'
55 -- , lscanlM'
56 -- , lscanl1'
57 -- , lscanl1M'
58 --
59 -- , lpostscanl'
60 -- , lpostscanlM'
61 -- , lprescanl'
62 -- , lprescanlM'
64 -- * Filtering
65 -- | Produce a subset of the stream.
67 , filter
68 , filterM
69 , deleteBy
70 , uniq
71 -- , uniqBy -- by predicate e.g. to remove duplicate "/" in a path
72 -- , uniqOn -- to remove duplicate sequences
73 -- , pruneBy -- dropAround + uniqBy - like words
75 -- * Trimming
76 -- | Produce a subset of the stream trimmed at ends.
78 , take
79 -- , takeGE
80 -- , takeBetween
81 , takeByTime
82 -- , takeEnd
83 , takeWhile
84 , takeWhileM
85 -- , takeWhileEnd
86 , drop
87 , dropByTime
88 -- , dropEnd
89 , dropWhile
90 , dropWhileM
91 -- , dropWhileEnd
92 -- , dropAround
94 -- * Inserting Elements
95 -- | Produce a superset of the stream.
97 , insertBy
98 , intersperse
99 , intersperseM -- XXX naming
100 , intersperseSuffix
101 , intersperseSuffixBySpan
102 -- , intersperseBySpan
103 -- , intersperseByIndices -- using an index function/stream
105 -- * Inserting Side Effects
106 , intersperseM_ -- XXX naming
107 , intersperseSuffix_
108 , interspersePrefix_
110 -- * Inserting Time
111 -- , intersperseByTime
112 -- , intersperseByEvent
113 , interjectSuffix
114 , delay
115 , delayPost
116 , delayPre
118 -- * Reordering
119 , reverse
120 , reverse'
121 , reassembleBy
123 -- * Position Indexing
124 , indexed
125 , indexedR
127 -- * Time Indexing
128 , timestamped
129 , timestampWith
130 -- , timestampedR -- timer
131 , timeIndexed
132 , timeIndexWith
134 -- * Searching
135 , findIndices -- XXX indicesBy
136 , elemIndices -- XXX indicesOf
138 -- * Rolling map
139 -- | Map using the previous element.
140 , rollingMapM
141 , rollingMap
143 -- * Maybe Streams
144 -- Move these to Streamly.Data.Maybe.Stream?
145 , catMaybes -- XXX justs (like lefts/rights)
146 , mapMaybe
147 , mapMaybeM
149 -- * Either Streams
150 -- Move these to Streamly.Data.Either.Stream?
151 , lefts
152 , rights
154 -- * Threading
155 -- ** Concurrent Pipelines
156 -- | Run streaming stages concurrently.
158 , Par.mkParallel
159 , applyAsync
160 , (|$)
161 , (|&)
163 -- ** Concurrency Control
164 , maxThreads
165 , maxBuffer
167 -- ** Rate Limiting
168 , Rate (..)
169 , rate
170 , avgRate
171 , minRate
172 , maxRate
173 , constRate
175 -- * Diagnostics
176 , inspectMode
178 -- * Deprecated
179 , scanx
180 )
181where
183#include "inline.hs"
185import Control.Concurrent (threadDelay)
186import Control.Monad (void)
187import Control.Monad.Catch (MonadCatch)
188import Control.Monad.IO.Class (MonadIO(..))
189import Control.Monad.Trans.Class (MonadTrans(..))
190import Data.Either (isLeft, isRight)
191import Data.Maybe (isJust, fromJust)
192import Streamly.Internal.BaseCompat (fromLeft, fromRight)
193import Streamly.Internal.Data.Fold.Types (Fold (..))
194import Streamly.Internal.Data.Pipe.Types (Pipe (..))
195import Streamly.Internal.Data.Stream.IsStream.Combinators
196 ( inspectMode, maxBuffer, maxThreads, rate, avgRate, minRate
197 , maxRate, constRate)
198import Streamly.Internal.Data.Stream.IsStream.Common
199 ( absTimesWith
200 , drop
201 , findIndices
202 , postscanlM'
203 , relTimesWith
204 , reverse
205 , reverse'
206 , scanlMAfter'
207 , smapM
208 , take
209 , takeWhile
210 , interjectSuffix
211 , intersperseM
212 )
213import Streamly.Internal.Data.Stream.Prelude (fromStreamS, toStreamS)
214import Streamly.Internal.Data.Stream.Serial (SerialT)
215import Streamly.Internal.Data.Stream.StreamD (fromStreamD, toStreamD)
216import Streamly.Internal.Data.Stream.StreamK (IsStream)
217import Streamly.Internal.Data.SVar (MonadAsync, Rate(..))
218import Streamly.Internal.Data.Time.Units ( TimeUnit64, AbsTime, RelTime64)
220import qualified Streamly.Internal.Data.Fold as FL
221import qualified Streamly.Internal.Data.Stream.Parallel as Par
222import qualified Streamly.Internal.Data.Stream.Prelude as P
223import qualified Streamly.Internal.Data.Stream.Serial as Serial
224import qualified Streamly.Internal.Data.Stream.StreamD as D
225import qualified Streamly.Internal.Data.Stream.StreamK as K
226import qualified Streamly.Internal.Data.Stream.Zip as Z
227#ifdef USE_STREAMK_ONLY
228import qualified Streamly.Internal.Data.Stream.StreamK as S
229#else
230import qualified Streamly.Internal.Data.Stream.StreamD as S
231#endif
233import Prelude hiding
234 ( filter, drop, dropWhile, take, takeWhile, foldr, map, mapM, sequence
235 , reverse, foldr1 , scanl, scanl1)
237------------------------------------------------------------------------------
238-- Piping
239------------------------------------------------------------------------------
241-- | Use a 'Pipe' to transform a stream.
242--
243-- /Internal/
244--
245{-# INLINE transform #-}
246transform :: (IsStream t, Monad m) => Pipe m a b -> t m a -> t m b
247transform pipe xs = fromStreamD $ D.transform pipe (toStreamD xs)
249------------------------------------------------------------------------------
250-- Transformation Folds
251------------------------------------------------------------------------------
253-- | Right fold to a streaming monad.
254--
255-- > foldrS S.cons S.nil === id
256--
257-- 'foldrS' can be used to perform stateless stream to stream transformations
258-- like map and filter in general. It can be coupled with a scan to perform
259-- stateful transformations. However, note that the custom map and filter
260-- routines can be much more efficient than this due to better stream fusion.
261--
262-- >>> S.toList $ S.foldrS S.cons S.nil $ S.fromList [1..5]
263-- > [1,2,3,4,5]
264--
265-- Find if any element in the stream is 'True':
266--
267-- >>> S.toList $ S.foldrS (\x xs -> if odd x then return True else xs) (return False) $ (S.fromList (2:4:5:undefined) :: SerialT IO Int)
268-- > [True]
269--
270-- Map (+2) on odd elements and filter out the even elements:
271--
272-- >>> S.toList $ S.foldrS (\x xs -> if odd x then (x + 2) `S.cons` xs else xs) S.nil $ (S.fromList [1..5] :: SerialT IO Int)
273-- > [3,5,7]
274--
275-- 'foldrM' can also be represented in terms of 'foldrS', however, the former
276-- is much more efficient:
277--
278-- > foldrM f z s = runIdentityT $ foldrS (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
279--
280-- /Internal/
281{-# INLINE foldrS #-}
282foldrS :: IsStream t => (a -> t m b -> t m b) -> t m b -> t m a -> t m b
283foldrS = K.foldrS
285-- | Right fold to a transformer monad. This is the most general right fold
286-- function. 'foldrS' is a special case of 'foldrT', however 'foldrS'
287-- implementation can be more efficient:
288--
289-- > foldrS = foldrT
290-- > foldrM f z s = runIdentityT $ foldrT (\x xs -> lift $ f x (runIdentityT xs)) (lift z) s
291--
292-- 'foldrT' can be used to translate streamly streams to other transformer
293-- monads e.g. to a different streaming type.
294--
295-- /Internal/
296{-# INLINE foldrT #-}
297foldrT :: (IsStream t, Monad m, Monad (s m), MonadTrans s)
298 => (a -> s m b -> s m b) -> s m b -> t m a -> s m b
299foldrT f z s = S.foldrT f z (toStreamS s)
301------------------------------------------------------------------------------
302-- Transformation by Mapping
303------------------------------------------------------------------------------
305-- |
306-- @
307-- mapM f = sequence . map f
308-- @
309--
310-- Apply a monadic function to each element of the stream and replace it with
311-- the output of the resulting action.
312--
313-- @
314-- > drain $ S.mapM putStr $ S.fromList ["a", "b", "c"]
315-- abc
316--
317-- drain $ S.replicateM 10 (return 1)
318-- & (serially . S.mapM (\\x -> threadDelay 1000000 >> print x))
319--
320-- drain $ S.replicateM 10 (return 1)
321-- & (asyncly . S.mapM (\\x -> threadDelay 1000000 >> print x))
322-- @
323--
324-- /Concurrent (do not use with 'parallely' on infinite streams)/
325--
326-- @since 0.1.0
327{-# INLINE_EARLY mapM #-}
328mapM :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m b
329mapM = K.mapM
331{-# RULES "mapM serial" mapM = mapMSerial #-}
332{-# INLINE mapMSerial #-}
333mapMSerial :: Monad m => (a -> m b) -> SerialT m a -> SerialT m b
334mapMSerial = Serial.mapM
336-- |
337-- @
338-- sequence = mapM id
339-- @
340--
341-- Replace the elements of a stream of monadic actions with the outputs of
342-- those actions.
343--
344-- @
345-- > drain $ S.sequence $ S.fromList [putStr "a", putStr "b", putStrLn "c"]
346-- abc
347--
348-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
349-- & (serially . S.sequence)
350--
351-- drain $ S.replicateM 10 (return $ threadDelay 1000000 >> print 1)
352-- & (asyncly . S.sequence)
353-- @
354--
355-- /Concurrent (do not use with 'parallely' on infinite streams)/
356--
357-- @since 0.1.0
358{-# INLINE sequence #-}
359sequence :: (IsStream t, MonadAsync m) => t m (m a) -> t m a
360sequence m = fromStreamS $ S.sequence (toStreamS m)
362------------------------------------------------------------------------------
363-- Mapping side effects
364------------------------------------------------------------------------------
366-- | Tap the data flowing through a stream into a 'Fold'. For example, you may
367-- add a tap to log the contents flowing through the stream. The fold is used
368-- only for effects, its result is discarded.
369--
370-- @
371-- Fold m a b
372-- |
373-- -----stream m a ---------------stream m a-----
374--
375-- @
376--
377-- @
378-- > S.drain $ S.tap (FL.drainBy print) (S.enumerateFromTo 1 2)
379-- 1
380-- 2
381-- @
382--
383-- Compare with 'trace'.
384--
385-- @since 0.7.0
386{-# INLINE tap #-}
387tap :: (IsStream t, Monad m) => FL.Fold m a b -> t m a -> t m a
388tap f xs = D.fromStreamD $ D.tap f (D.toStreamD xs)
390-- | @tapOffsetEvery offset n@ taps every @n@th element in the stream
391-- starting at @offset@. @offset@ can be between @0@ and @n - 1@. Offset 0
392-- means start at the first element in the stream. If the offset is outside
393-- this range then @offset `mod` n@ is used as offset.
394--
395-- @
396-- >>> S.drain $ S.tapOffsetEvery 0 2 (FL.rmapM print FL.toList) $ S.enumerateFromTo 0 10
397-- > [0,2,4,6,8,10]
398-- @
399--
400-- /Internal/
401--
402{-# INLINE tapOffsetEvery #-}
403tapOffsetEvery :: (IsStream t, Monad m)
404 => Int -> Int -> FL.Fold m a b -> t m a -> t m a
405tapOffsetEvery offset n f xs =
406 D.fromStreamD $ D.tapOffsetEvery offset n f (D.toStreamD xs)
408-- | Redirect a copy of the stream to a supplied fold and run it concurrently
409-- in an independent thread. The fold may buffer some elements. The buffer size
410-- is determined by the prevailing 'maxBuffer' setting.
411--
412-- @
413-- Stream m a -> m b
414-- |
415-- -----stream m a ---------------stream m a-----
416--
417-- @
418--
419-- @
420-- > S.drain $ S.tapAsync (S.mapM_ print) (S.enumerateFromTo 1 2)
421-- 1
422-- 2
423-- @
424--
425-- Exceptions from the concurrently running fold are propagated to the current
426-- computation. Note that, because of buffering in the fold, exceptions may be
427-- delayed and may not correspond to the current element being processed in the
428-- parent stream, but we guarantee that before the parent stream stops the tap
429-- finishes and all exceptions from it are drained.
430--
431--
432-- Compare with 'tap'.
433--
434-- /Internal/
435{-# INLINE tapAsync #-}
436tapAsync :: (IsStream t, MonadAsync m) => FL.Fold m a b -> t m a -> t m a
437tapAsync f xs = D.fromStreamD $ Par.tapAsyncF f (D.toStreamD xs)
439-- | @pollCounts predicate transform fold stream@ counts those elements in the
440-- stream that pass the @predicate@. The resulting count stream is sent to
441-- another thread which transforms it using @transform@ and then folds it using
442-- @fold@. The thread is automatically cleaned up if the stream stops or
443-- aborts due to exception.
444--
445-- For example, to print the count of elements processed every second:
446--
447-- @
448-- > S.drain $ S.pollCounts (const True) (S.rollingMap (-) . S.delayPost 1) (FL.drainBy print)
449-- $ S.enumerateFrom 0
450-- @
451--
452-- Note: This may not work correctly on 32-bit machines.
453--
454-- /Internal/
455--
456{-# INLINE pollCounts #-}
457pollCounts ::
458 (IsStream t, MonadAsync m)
459 => (a -> Bool)
460 -> (t m Int -> t m Int)
461 -> Fold m Int b
462 -> t m a
463 -> t m a
464pollCounts predicate transf f xs =
465 D.fromStreamD
466 $ D.pollCounts predicate (D.toStreamD . transf . D.fromStreamD) f
467 $ D.toStreamD xs
469-- | Calls the supplied function with the number of elements consumed
470-- every @n@ seconds. The given function is run in a separate thread
471-- until the end of the stream. In case there is an exception in the
472-- stream the thread is killed during the next major GC.
473--
474-- Note: The action is not guaranteed to run if the main thread exits.
475--
476-- @
477-- > delay n = threadDelay (round $ n * 1000000) >> return n
478-- > S.drain $ S.tapRate 2 (\\n -> print $ show n ++ " elements processed") (delay 1 S.|: delay 0.5 S.|: delay 0.5 S.|: S.nil)
479-- 2 elements processed
480-- 1 elements processed
481-- @
482--
483-- Note: This may not work correctly on 32-bit machines.
484--
485-- /Internal/
486{-# INLINE tapRate #-}
487tapRate ::
488 (IsStream t, MonadAsync m, MonadCatch m)
489 => Double
490 -> (Int -> m b)
491 -> t m a
492 -> t m a
493tapRate n f xs = D.fromStreamD $ D.tapRate n f $ D.toStreamD xs
495-- | Apply a monadic function to each element flowing through the stream and
496-- discard the results.
497--
498-- @
499-- > S.drain $ S.trace print (S.enumerateFromTo 1 2)
500-- 1
501-- 2
502-- @
503--
504-- Compare with 'tap'.
505--
506-- @since 0.7.0
507{-# INLINE trace #-}
508trace :: (IsStream t, MonadAsync m) => (a -> m b) -> t m a -> t m a
509trace f = mapM (\x -> void (f x) >> return x)
511-- | Perform a side effect before yielding each element of the stream and
512-- discard the results.
513--
514-- @
515-- > S.drain $ S.trace_ (print "got here") (S.enumerateFromTo 1 2)
516-- "got here"
517-- "got here"
518-- @
519--
520-- See also: 'trace', 'interspersePrefix_'
521--
522-- /Internal/
523{-# INLINE trace_ #-}
524trace_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
525trace_ eff = Serial.mapM (\x -> eff >> return x)
527------------------------------------------------------------------------------
528-- Scanning with a Fold
529------------------------------------------------------------------------------
531-- | Scan a stream using the given monadic fold.
532--
533-- @since 0.7.0
534{-# INLINE scan #-}
535scan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
536scan = P.scanOnce
538-- | Postscan a stream using the given monadic fold.
539--
540-- @since 0.7.0
541{-# INLINE postscan #-}
542postscan :: (IsStream t, Monad m) => Fold m a b -> t m a -> t m b
543postscan = P.postscanOnce
545------------------------------------------------------------------------------
546-- Scanning - Transformation by Folding
547------------------------------------------------------------------------------
549-- XXX It may be useful to have a version of scan where we can keep the
550-- accumulator independent of the value emitted. So that we do not necessarily
551-- have to keep a value in the accumulator which we are not using. We can pass
552-- an extraction function that will take the accumulator and the current value
553-- of the element and emit the next value in the stream. That will also make it
554-- possible to modify the accumulator after using it. In fact, the step function
555-- can return new accumulator and the value to be emitted. The signature would
556-- be more like mapAccumL. Or we can change the signature of scanx to
557-- accommodate this.
558--
559-- | Strict left scan with an extraction function. Like 'scanl'', but applies a
560-- user supplied extraction function (the third argument) at each step. This is
561-- designed to work with the @foldl@ library. The suffix @x@ is a mnemonic for
562-- extraction.
563--
564-- /Since 0.2.0/
565--
566-- /Since: 0.7.0 (Monad m constraint)/
567{-# DEPRECATED scanx "Please use scanl followed by map instead." #-}
568{-# INLINE scanx #-}
569scanx :: (IsStream t, Monad m) => (x -> a -> x) -> x -> (x -> b) -> t m a -> t m b
570scanx = P.scanlx'
572-- XXX this needs to be concurrent
573-- XXX because of the use of D.cons for appending, scanlM' has quadratic
574-- complexity when iterated over a stream. We should use StreamK style scanlM'
575-- for linear performance on iteration.
576--
577-- | Like 'scanl'' but with a monadic step function and a monadic seed.
578--
579-- /Since: 0.4.0/
580--
581-- /Since: 0.8.0 (signature change)/
582{-# INLINE scanlM' #-}
583scanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
584scanlM' step begin m = fromStreamD $ D.scanlM' step begin $ toStreamD m
586-- XXX because of the use of D.cons for appending, scanl' has quadratic
587-- complexity when iterated over a stream. We should use StreamK style scanlM'
588-- for linear performance on iteration.
590-- | Strict left scan. Like 'map', 'scanl'' too is a one to one transformation,
591-- however it adds an extra element.
592--
593-- @
594-- > S.toList $ S.scanl' (+) 0 $ fromList [1,2,3,4]
595-- [0,1,3,6,10]
596-- @
597--
598-- @
599-- > S.toList $ S.scanl' (flip (:)) [] $ S.fromList [1,2,3,4]
600-- [[],[1],[2,1],[3,2,1],[4,3,2,1]]
601-- @
602--
603-- The output of 'scanl'' is the initial value of the accumulator followed by
604-- all the intermediate steps and the final result of 'foldl''.
605--
606-- By streaming the accumulated state after each fold step, we can share the
607-- state across multiple stages of stream composition. Each stage can modify or
608-- extend the state, do some processing with it and emit it for the next stage,
609-- thus modularizing the stream processing. This can be useful in
610-- stateful or event-driven programming.
611--
612-- Consider the following monolithic example, computing the sum and the product
613-- of the elements in a stream in one go using a @foldl'@:
614--
615-- @
616-- > S.foldl' (\\(s, p) x -> (s + x, p * x)) (0,1) $ S.fromList \[1,2,3,4]
617-- (10,24)
618-- @
619--
620-- Using @scanl'@ we can make it modular by computing the sum in the first
621-- stage and passing it down to the next stage for computing the product:
622--
623-- @
624-- > S.foldl' (\\(_, p) (s, x) -> (s, p * x)) (0,1)
625-- $ S.scanl' (\\(s, _) x -> (s + x, x)) (0,1)
626-- $ S.fromList \[1,2,3,4]
627-- (10,24)
628-- @
629--
630-- IMPORTANT: 'scanl'' evaluates the accumulator to WHNF. To avoid building
631-- lazy expressions inside the accumulator, it is recommended that a strict
632-- data structure is used for accumulator.
633--
634-- See also: 'usingStateT'
635--
636-- @since 0.2.0
637{-# INLINE scanl' #-}
638scanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
639scanl' step z m = fromStreamS $ S.scanl' step z $ toStreamS m
641-- | Like 'scanl'' but does not stream the initial value of the accumulator.
642--
643-- > postscanl' f z xs = S.drop 1 $ S.scanl' f z xs
644--
645-- @since 0.7.0
646{-# INLINE postscanl' #-}
647postscanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
648postscanl' step z m = fromStreamD $ D.postscanl' step z $ toStreamD m
650-- XXX prescanl does not sound very useful, enable only if there is a
651-- compelling use case.
652--
653-- | Like scanl' but does not stream the final value of the accumulator.
654--
655-- /Internal/
656{-# INLINE prescanl' #-}
657prescanl' :: (IsStream t, Monad m) => (b -> a -> b) -> b -> t m a -> t m b
658prescanl' step z m = fromStreamD $ D.prescanl' step z $ toStreamD m
660-- XXX this needs to be concurrent
661-- | Like prescanl' but with a monadic step function and a monadic seed.
662--
663-- /Internal/
664{-# INLINE prescanlM' #-}
665prescanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
666prescanlM' step z m = fromStreamD $ D.prescanlM' step z $ toStreamD m
668-- XXX this needs to be concurrent
669-- | Like 'scanl1'' but with a monadic step function.
670--
671-- @since 0.6.0
672{-# INLINE scanl1M' #-}
673scanl1M' :: (IsStream t, Monad m) => (a -> a -> m a) -> t m a -> t m a
674scanl1M' step m = fromStreamD $ D.scanl1M' step $ toStreamD m
676-- | Like 'scanl'' but for a non-empty stream. The first element of the stream
677-- is used as the initial value of the accumulator. Does nothing if the stream
678-- is empty.
679--
680-- @
681-- > S.toList $ S.scanl1 (+) $ fromList [1,2,3,4]
682-- [1,3,6,10]
683-- @
684--
685-- @since 0.6.0
686{-# INLINE scanl1' #-}
687scanl1' :: (IsStream t, Monad m) => (a -> a -> a) -> t m a -> t m a
688scanl1' step m = fromStreamD $ D.scanl1' step $ toStreamD m
690------------------------------------------------------------------------------
691-- Filtering
692------------------------------------------------------------------------------
694-- | Include only those elements that pass a predicate.
695--
696-- @since 0.1.0
697{-# INLINE filter #-}
698#if __GLASGOW_HASKELL__ != 802
699-- GHC 8.2.2 crashes with this code, when used with "stack"
700filter :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
701filter p m = fromStreamS $ S.filter p $ toStreamS m
702#else
703filter :: IsStream t => (a -> Bool) -> t m a -> t m a
704filter = K.filter
705#endif
707-- | Same as 'filter' but with a monadic predicate.
708--
709-- @since 0.4.0
710{-# INLINE filterM #-}
711filterM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
712filterM p m = fromStreamD $ D.filterM p $ toStreamD m
714-- | Drop repeated elements that are adjacent to each other.
715--
716-- @since 0.6.0
717{-# INLINE uniq #-}
718uniq :: (Eq a, IsStream t, Monad m) => t m a -> t m a
719uniq = fromStreamD . D.uniq . toStreamD
721-- | Deletes the first occurrence of the element in the stream that satisfies
722-- the given equality predicate.
723--
724-- @
725-- > S.toList $ S.deleteBy (==) 3 $ S.fromList [1,3,3,5]
726-- [1,3,5]
727-- @
728--
729-- @since 0.6.0
730{-# INLINE deleteBy #-}
731deleteBy :: (IsStream t, Monad m) => (a -> a -> Bool) -> a -> t m a -> t m a
732deleteBy cmp x m = fromStreamS $ S.deleteBy cmp x (toStreamS m)
734------------------------------------------------------------------------------
735-- Trimming
736------------------------------------------------------------------------------
738-- | Same as 'takeWhile' but with a monadic predicate.
739--
740-- @since 0.4.0
741{-# INLINE takeWhileM #-}
742takeWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
743takeWhileM p m = fromStreamD $ D.takeWhileM p $ toStreamD m
745-- | @takeByTime duration@ yields stream elements upto specified time
746-- @duration@. The duration starts when the stream is evaluated for the first
747-- time, before the first element is yielded. The time duration is checked
748-- before generating each element, if the duration has expired the stream
749-- stops.
750--
751-- The total time taken in executing the stream is guaranteed to be /at least/
752-- @duration@, however, because the duration is checked before generating an
753-- element, the upper bound is indeterminate and depends on the time taken in
754-- generating and processing the last element.
755--
756-- No element is yielded if the duration is zero. At least one element is
757-- yielded if the duration is non-zero.
758--
759-- /Internal/
760--
761{-# INLINE takeByTime #-}
762takeByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
763takeByTime d = fromStreamD . D.takeByTime d . toStreamD
765-- | Drop elements in the stream as long as the predicate succeeds and then
766-- take the rest of the stream.
767--
768-- @since 0.1.0
769{-# INLINE dropWhile #-}
770dropWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
771dropWhile p m = fromStreamS $ S.dropWhile p $ toStreamS m
773-- | Same as 'dropWhile' but with a monadic predicate.
774--
775-- @since 0.4.0
776{-# INLINE dropWhileM #-}
777dropWhileM :: (IsStream t, Monad m) => (a -> m Bool) -> t m a -> t m a
778dropWhileM p m = fromStreamD $ D.dropWhileM p $ toStreamD m
780-- | @dropByTime duration@ drops stream elements until specified @duration@ has
781-- passed. The duration begins when the stream is evaluated for the first
782-- time. The time duration is checked /after/ generating a stream element, the
783-- element is yielded if the duration has expired otherwise it is dropped.
784--
785-- The time elapsed before starting to generate the first element is /at most/
786-- @duration@, however, because the duration expiry is checked after the
787-- element is generated, the lower bound is indeterminate and depends on the
788-- time taken in generating an element.
789--
790-- All elements are yielded if the duration is zero.
791--
792-- /Internal/
793--
794{-# INLINE dropByTime #-}
795dropByTime ::(MonadIO m, IsStream t, TimeUnit64 d) => d -> t m a -> t m a
796dropByTime d = fromStreamD . D.dropByTime d . toStreamD
798------------------------------------------------------------------------------
799-- Inserting Elements
800------------------------------------------------------------------------------
802-- | @insertBy cmp elem stream@ inserts @elem@ before the first element in
803-- @stream@ that is less than @elem@ when compared using @cmp@.
804--
805-- @
806-- insertBy cmp x = 'mergeBy' cmp ('yield' x)
807-- @
808--
809-- @
810-- > S.toList $ S.insertBy compare 2 $ S.fromList [1,3,5]
811-- [1,2,3,5]
812-- @
813--
814-- @since 0.6.0
815{-# INLINE insertBy #-}
816insertBy ::
817 (IsStream t, Monad m) => (a -> a -> Ordering) -> a -> t m a -> t m a
818insertBy cmp x m = fromStreamS $ S.insertBy cmp x (toStreamS m)
820-- | Insert a pure value between successive elements of a stream.
821--
822-- @
823-- > S.toList $ S.intersperse ',' $ S.fromList "hello"
824-- "h,e,l,l,o"
825-- @
826--
827-- @since 0.7.0
828{-# INLINE intersperse #-}
829intersperse :: (IsStream t, MonadAsync m) => a -> t m a -> t m a
830intersperse a = fromStreamS . S.intersperse a . toStreamS
832-- | Insert a side effect before consuming an element of a stream except the
833-- first one.
834--
835-- @
836-- >>> S.drain $ S.trace putChar $ S.intersperseM_ (putChar '.') $ S.fromList "hello"
837-- > h.e.l.l.o
838-- @
839--
840-- /Internal/
841{-# INLINE intersperseM_ #-}
842intersperseM_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
843intersperseM_ m = fromStreamD . D.intersperseM_ m . toStreamD
845{-
846-- | Intersperse a monadic action into the input stream after every @n@
847-- elements.
848--
849-- @
850-- > S.toList $ S.intersperseBySpan 2 (return ',') $ S.fromList "hello"
851-- "he,ll,o"
852-- @
853--
854-- @since 0.7.0
855{-# INLINE intersperseBySpan #-}
856intersperseBySpan :: IsStream t => Int -> m a -> t m a -> t m a
857intersperseBySpan _n _f _xs = undefined
858-}
860-- | Insert an effect and its output after consuming an element of a stream.
861--
862-- @
863-- >>> S.toList $ S.trace putChar $ S.intersperseSuffix (putChar '.' >> return ',') $ S.fromList "hello"
864-- > h.,e.,l.,l.,o.,"h,e,l,l,o,"
865-- @
866--
867-- /Internal/
868{-# INLINE intersperseSuffix #-}
869intersperseSuffix :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
870intersperseSuffix m = fromStreamD . D.intersperseSuffix m . toStreamD
872-- | Insert a side effect after consuming an element of a stream.
873--
874-- @
875-- > S.mapM_ putChar $ S.intersperseSuffix_ (threadDelay 1000000) $ S.fromList "hello"
876-- @
877--
878-- /Internal/
879--
880{-# INLINE intersperseSuffix_ #-}
881intersperseSuffix_ :: (IsStream t, Monad m) => m b -> t m a -> t m a
882intersperseSuffix_ m = fromStreamD . D.intersperseSuffix_ m . toStreamD
884-- | Like 'intersperseSuffix' but intersperses an effectful action into the
885-- input stream after every @n@ elements and after the last element.
886--
887-- @
888-- > S.toList $ S.intersperseSuffixBySpan 2 (return ',') $ S.fromList "hello"
889-- "he,ll,o,"
890-- @
891--
892-- /Internal/
893--
894{-# INLINE intersperseSuffixBySpan #-}
895intersperseSuffixBySpan :: (IsStream t, MonadAsync m)
896 => Int -> m a -> t m a -> t m a
897intersperseSuffixBySpan n eff =
898 fromStreamD . D.intersperseSuffixBySpan n eff . toStreamD
900-- | Insert a side effect before consuming an element of a stream.
901--
902-- @
903-- >>> S.toList $ S.trace putChar $ S.interspersePrefix_ (putChar '.' >> return ',') $ S.fromList "hello"
904-- > .h.e.l.l.o"hello"
905-- @
906--
907-- See also: 'trace_'
908--
909-- /Concurrent/
910--
911-- /Internal/
912--
913{-# INLINE interspersePrefix_ #-}
914interspersePrefix_ :: (IsStream t, MonadAsync m) => m b -> t m a -> t m a
915interspersePrefix_ m = mapM (\x -> void m >> return x)
917------------------------------------------------------------------------------
918-- Inserting Time
919------------------------------------------------------------------------------
921-- Note: delay must be serial.
922--
923-- | Introduce a delay of specified seconds before consuming an element of the
924-- stream except the first one.
925--
926-- @
927-- >>> S.mapM_ print $ S.timestamped $ S.delay 1 $ S.enumerateFromTo 1 3
928-- > (AbsTime (TimeSpec {sec = 2502706, nsec = 751137000}),1)
929-- > (AbsTime (TimeSpec {sec = 2502707, nsec = 743535000}),2)
930-- > (AbsTime (TimeSpec {sec = 2502708, nsec = 749758000}),3)
931-- @
932--
933-- /Internal/
934--
935{-# INLINE delay #-}
936delay :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
937delay n = intersperseM_ $ liftIO $ threadDelay $ round $ n * 1000000
939-- Note: delay must be serial.
940--
941-- | Introduce a delay of specified seconds after consuming an element of a
942-- stream.
943--
944-- @
945-- >>> S.mapM_ print $ S.timestamped $ S.delayPost 1 $ S.enumerateFromTo 1 3
946-- > (AbsTime (TimeSpec {sec = 2502826, nsec = 119030000}),1)
947-- > (AbsTime (TimeSpec {sec = 2502827, nsec = 111393000}),2)
948-- > (AbsTime (TimeSpec {sec = 2502828, nsec = 112221000}),3)
949-- @
950--
951-- /Internal/
952--
953{-# INLINE delayPost #-}
954delayPost :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
955delayPost n = intersperseSuffix_ $ liftIO $ threadDelay $ round $ n * 1000000
957-- Note: delay must be serial, that's why 'trace_' is used.
958--
959-- | Introduce a delay of specified seconds before consuming an element of a
960-- stream.
961--
962-- @
963-- >>> S.mapM_ print $ S.timestamped $ S.delayPre 1 $ S.enumerateFromTo 1 3
964-- > (AbsTime (TimeSpec {sec = 2502207, nsec = 533177000}),1)
965-- > (AbsTime (TimeSpec {sec = 2502208, nsec = 530859000}),2)
966-- > (AbsTime (TimeSpec {sec = 2502209, nsec = 531619000}),3)
967-- @
968--
969-- /Internal/
970--
971{-# INLINE delayPre #-}
972delayPre :: (IsStream t, MonadIO m) => Double -> t m a -> t m a
973delayPre n = trace_ $ liftIO $ threadDelay $ round $ n * 1000000
975------------------------------------------------------------------------------
976-- Reorder in sequence
977------------------------------------------------------------------------------
979-- | Buffer until the next element in sequence arrives. The function argument
980-- determines the difference in sequence numbers. This could be useful in
981-- implementing sequenced streams, for example, TCP reassembly.
982--
983-- /Unimplemented/
984--
985{-# INLINE reassembleBy #-}
986reassembleBy
987 :: -- (IsStream t, Monad m) =>
988 Fold m a b
989 -> (a -> a -> Int)
990 -> t m a
991 -> t m b
992reassembleBy = undefined
994------------------------------------------------------------------------------
995-- Position Indexing
996------------------------------------------------------------------------------
998-- |
999-- > indexed = S.postscanl' (\(i, _) x -> (i + 1, x)) (-1,undefined)
1000-- > indexed = S.zipWith (,) (S.enumerateFrom 0)
1002-- Pair each element in a stream with its index, starting from index 0.
1004-- @
1005-- > S.toList $ S.indexed $ S.fromList "hello"
1006-- [(0,'h'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
1007-- @
1009-- @since 0.6.0
1010{-# INLINE indexed #-}
1011indexed :: (IsStream t, Monad m) => t m a -> t m (Int, a)
1012indexed = fromStreamD . D.indexed . toStreamD
1014-- |
1015-- > indexedR n = S.postscanl' (\(i, _) x -> (i - 1, x)) (n + 1,undefined)
1016-- > indexedR n = S.zipWith (,) (S.enumerateFromThen n (n - 1))
1018-- Pair each element in a stream with its index, starting from the
1019-- given index @n@ and counting down.
1021-- @
1022-- > S.toList $ S.indexedR 10 $ S.fromList "hello"
1023-- [(10,'h'),(9,'e'),(8,'l'),(7,'l'),(6,'o')]
1024-- @
1026-- @since 0.6.0
1027{-# INLINE indexedR #-}
1028indexedR :: (IsStream t, Monad m) => Int -> t m a -> t m (Int, a)
1029indexedR n = fromStreamD . D.indexedR n . toStreamD
1031-------------------------------------------------------------------------------
1032-- Time Indexing
1033-------------------------------------------------------------------------------
1035-- Note: The timestamp stream must be the second stream in the zip so that the
1036-- timestamp is generated after generating the stream element and not before.
1037-- If we do not do that then the following example will generate the same
1038-- timestamp for first two elements:
1040-- S.mapM_ print $ S.timestamped $ S.delay $ S.enumerateFromTo 1 3
1042-- | Pair each element in a stream with an absolute timestamp, using a clock of
1043-- specified granularity. The timestamp is generated just before the element
1044-- is consumed.
1046-- @
1047-- >>> S.mapM_ print $ S.timestampWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1048-- @
1050-- /Internal/
1052{-# INLINE timestampWith #-}
1053timestampWith :: (IsStream t, MonadAsync m, Functor (t m))
1054 => Double -> t m a -> t m (AbsTime, a)
1055timestampWith g stream = Z.zipWith (flip (,)) stream (absTimesWith g)
1057-- TBD: check performance vs a custom implementation without using zipWith.
1059-- /Internal/
1061{-# INLINE timestamped #-}
1062timestamped :: (IsStream t, MonadAsync m, Functor (t m))
1063 => t m a -> t m (AbsTime, a)
1064timestamped = timestampWith 0.01
1066-- | Pair each element in a stream with relative times starting from 0, using a
1067-- clock with the specified granularity. The time is measured just before the
1068-- element is consumed.
1070-- @
1071-- >>> S.mapM_ print $ S.timeIndexWith 0.01 $ S.delay 1 $ S.enumerateFromTo 1 3
1072-- @
1074-- /Internal/
1076{-# INLINE timeIndexWith #-}
1077timeIndexWith :: (IsStream t, MonadAsync m, Functor (t m))
1078 => Double -> t m a -> t m (RelTime64, a)
1079timeIndexWith g stream = Z.zipWith (flip (,)) stream (relTimesWith g)
1081-- | Pair each element in a stream with relative times starting from 0, using a
1082-- 10 ms granularity clock. The time is measured just before the element is
1083-- consumed.
1085-- @
1086-- >>> S.mapM_ print $ S.timeIndexed $ S.delay 1 $ S.enumerateFromTo 1 3
1087-- (RelTime64 (NanoSecond64 0),1)
1088-- (RelTime64 (NanoSecond64 996239000),2)
1089-- (RelTime64 (NanoSecond64 1996712000),3)
1090-- @
1092-- /Internal/
1094{-# INLINE timeIndexed #-}
1095timeIndexed :: (IsStream t, MonadAsync m, Functor (t m))
1096 => t m a -> t m (RelTime64, a)
1097timeIndexed = timeIndexWith 0.01
1099------------------------------------------------------------------------------
1100-- Searching
1101------------------------------------------------------------------------------
1103-- | Find all the indices where the value of the element in the stream is equal
1104-- to the given value.
1106-- > elemIndices a = findIndices (== a)
1108-- @since 0.5.0
1109{-# INLINE elemIndices #-}
1110elemIndices :: (IsStream t, Eq a, Monad m) => a -> t m a -> t m Int
1111elemIndices a = findIndices (== a)
1113------------------------------------------------------------------------------
1114-- Rolling map
1115------------------------------------------------------------------------------
1117-- XXX this is not a one-to-one map so calling it map may not be right.
1118-- We can perhaps call it zipWithTail or rollWith.
1120-- | Apply a function on every two successive elements of a stream. If the
1121-- stream consists of a single element the output is an empty stream.
1123-- This is the stream equivalent of the list idiom @zipWith f xs (tail xs)@.
1125-- /Internal/
1127{-# INLINE rollingMap #-}
1128rollingMap :: (IsStream t, Monad m) => (a -> a -> b) -> t m a -> t m b
1129rollingMap f m = fromStreamD $ D.rollingMap f $ toStreamD m
1131-- | Like 'rollingMap' but with an effectful map function.
1133-- /Internal/
1135{-# INLINE rollingMapM #-}
1136rollingMapM :: (IsStream t, Monad m) => (a -> a -> m b) -> t m a -> t m b
1137rollingMapM f m = fromStreamD $ D.rollingMapM f $ toStreamD m
1139------------------------------------------------------------------------------
1140-- Maybe Streams
1141------------------------------------------------------------------------------
1143-- | Map a 'Maybe' returning function to a stream, filter out the 'Nothing'
1144-- elements, and return a stream of values extracted from 'Just'.
1146-- Equivalent to:
1148-- @
1149-- mapMaybe f = S.map 'fromJust' . S.filter 'isJust' . S.map f
1150-- @
1152-- @since 0.3.0
1153{-# INLINE mapMaybe #-}
1154mapMaybe :: (IsStream t, Monad m) => (a -> Maybe b) -> t m a -> t m b
1155mapMaybe f m = fromStreamS $ S.mapMaybe f $ toStreamS m
1157-- | Like 'mapMaybe' but maps a monadic function.
1159-- Equivalent to:
1161-- @
1162-- mapMaybeM f = S.map 'fromJust' . S.filter 'isJust' . S.mapM f
1163-- @
1165-- /Concurrent (do not use with 'parallely' on infinite streams)/
1167-- @since 0.3.0
1168{-# INLINE_EARLY mapMaybeM #-}
1169mapMaybeM :: (IsStream t, MonadAsync m, Functor (t m))
1170 => (a -> m (Maybe b)) -> t m a -> t m b
1171mapMaybeM f = fmap fromJust . filter isJust . K.mapM f
1173{-# RULES "mapMaybeM serial" mapMaybeM = mapMaybeMSerial #-}
1174{-# INLINE mapMaybeMSerial #-}
1175mapMaybeMSerial :: Monad m => (a -> m (Maybe b)) -> SerialT m a -> SerialT m b
1176mapMaybeMSerial f m = fromStreamD $ D.mapMaybeM f $ toStreamD m
1178-- | In a stream of 'Maybe's, discard 'Nothing's and unwrap 'Just's.
1180-- /Internal/
1182catMaybes :: (IsStream t, Monad m, Functor (t m)) => t m (Maybe a) -> t m a
1183catMaybes = fmap fromJust . filter isJust
1185------------------------------------------------------------------------------
1186-- Either streams
1187------------------------------------------------------------------------------
1189-- | Discard 'Right's and unwrap 'Left's in an 'Either' stream.
1191-- /Internal/
1193lefts :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m a
1194lefts = fmap (fromLeft undefined) . filter isLeft
1196-- | Discard 'Left's and unwrap 'Right's in an 'Either' stream.
1198-- /Internal/
1200rights :: (IsStream t, Monad m, Functor (t m)) => t m (Either a b) -> t m b
1201rights = fmap (fromRight undefined) . filter isRight
1203------------------------------------------------------------------------------
1204-- Concurrent Application
1205------------------------------------------------------------------------------
1207-- | Parallel transform application operator; applies a stream transformation
1208-- function @t m a -> t m b@ to a stream @t m a@ concurrently; the input stream
1209-- is evaluated asynchronously in an independent thread yielding elements to a
1210-- buffer and the transformation function runs in another thread consuming the
1211-- input from the buffer. '|$' is just like regular function application
1212-- operator '$' except that it is concurrent.
1214-- If you read the signature as @(t m a -> t m b) -> (t m a -> t m b)@ you can
1215-- look at it as a transformation that converts a transform function to a
1216-- buffered concurrent transform function.
1218-- The following code prints a value every second even though each stage adds a
1219-- 1 second delay.
1222-- @
1223-- drain $
1224-- S.mapM (\\x -> threadDelay 1000000 >> print x)
1225-- |$ S.repeatM (threadDelay 1000000 >> return 1)
1226-- @
1228-- /Concurrent/
1230-- /Since: 0.3.0 ("Streamly")/
1232-- @since 0.8.0
1233{-# INLINE (|$) #-}
1234(|$) :: (IsStream t, MonadAsync m) => (t m a -> t m b) -> (t m a -> t m b)
1235-- (|$) f = f . Async.mkAsync
1236(|$) f = f . Par.mkParallel
1238infixr 0 |$
1240-- | Same as '|$'.
1242-- /Internal/
1244{-# INLINE applyAsync #-}
1245applyAsync :: (IsStream t, MonadAsync m)
1246 => (t m a -> t m b) -> (t m a -> t m b)
1247applyAsync = (|$)
1249-- | Parallel reverse function application operator for streams; just like the
1250-- regular reverse function application operator '&' except that it is
1251-- concurrent.
1253-- @
1254-- drain $
1255-- S.repeatM (threadDelay 1000000 >> return 1)
1256-- |& S.mapM (\\x -> threadDelay 1000000 >> print x)
1257-- @
1259-- /Concurrent/
1261-- /Since: 0.3.0 ("Streamly")/
1263-- @since 0.8.0
1264{-# INLINE (|&) #-}
1265(|&) :: (IsStream t, MonadAsync m) => t m a -> (t m a -> t m b) -> t m b
1266x |& f = f |$ x
1268infixl 1 |&