on eaaefcf help sign in
747 lines 26 kB history raw
1{-# OPTIONS_GHC -Wno-deprecations #-}
2{-# OPTIONS_GHC -Wno-orphans #-}
4-- |
5-- Module : Streamly.Internal.Data.Stream.IsStream.Common
6-- Copyright : (c) 2017 Composewell Technologies
7-- License : BSD-3-Clause
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
10-- Portability : GHC
11--
12-- Bottom level IsStream module that can be used by all other upper level
13-- IsStream modules.
15module Streamly.Internal.Data.Stream.IsStream.Common {-# DEPRECATED "Please use \"Streamly.Data.Stream.*\" instead." #-}
16 (
17 -- * Generation
18 fromPure
19 , fromEffect
20 , repeatM
21 , timesWith
22 , absTimesWith
23 , relTimesWith
25 -- * Elimination
26 , foldContinue
27 , fold
29 -- * Transformation
30 , map
31 , scanlMAfter'
32 , postscanlMAfter'
33 , postscanlM'
34 , smapM
35 , foldManyPost
36 -- $smapM_Notes
37 , take
38 , takeWhile
39 , takeEndBy
40 , drop
41 , findIndices
42 , intersperseM
43 , interjectSuffix
44 , reverse
45 , reverse'
47 -- * Concurrent
48 , mkAsync
49 , mkParallel
50 , parallelFst
52 -- * Nesting
53 , concatM
54 , concatMapM
55 , concatMap
56 , splitOnSeq
58 -- * Zipping
59 , zipWithM
60 , zipWith
62 -- * Deprecated
63 , yield
64 , yieldM
65 )
66where
68#include "inline.hs"
70import Control.Concurrent (threadDelay)
71import Control.Monad.IO.Class (MonadIO(..))
72import Foreign.Storable (Storable)
73import Streamly.Internal.Control.Concurrent (MonadAsync)
74import Streamly.Internal.Data.Array.Type (Array)
75import Streamly.Internal.Data.Fold.Type (Fold (..))
76import Streamly.Internal.Data.Stream.IsStream.Combinators (maxYields)
77import Streamly.Internal.Data.Stream.IsStream.Type
78 (IsStream(..), fromStreamD, toStreamD)
79import Streamly.Internal.Data.Stream.Serial (SerialT)
80import Streamly.Internal.Data.Time.Units (AbsTime, RelTime64, addToAbsTime64)
81import Streamly.Internal.System.IO (defaultChunkSize)
82import Streamly.Internal.Data.Unboxed (Unbox)
84import qualified Streamly.Internal.Data.Array.Type as A
85import qualified Streamly.Internal.Data.Stream.Async as Async
86import qualified Streamly.Internal.Data.Stream.IsStream.Type as IsStream
87import qualified Streamly.Internal.Data.Stream.Parallel as Par
88import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
89 (fromPure, fromEffect, repeatMWith, reverse)
90import qualified Streamly.Internal.Data.Stream.StreamD as D
91 (repeatM, timesWith, foldAddLazy, map, scanlMAfter', postscanlMAfter'
92 , postscanlM', take, takeWhile, takeEndBy, drop, findIndices
93 , fromStreamK, toStreamK, concatMapM, concatMap, foldManyPost, splitOnSeq
94 , zipWithM, zipWith, intersperseM, reverse, fold)
96import Prelude hiding (take, takeWhile, drop, reverse, concatMap, map, zipWith)
98--
99-- $setup
100-- >>> :m
101-- >>> :set -fno-warn-deprecations
102-- >>> import Control.Concurrent (threadDelay)
103-- >>> import Control.Monad (join)
104-- >>> import Control.Monad.Trans.Class (lift)
105-- >>> import Data.Function (fix, (&))
106-- >>> import Data.Semigroup (cycle1)
107-- >>> import Prelude hiding (take, takeWhile, drop, reverse)
108-- >>> import System.IO.Unsafe (unsafePerformIO)
109-- >>> import qualified Streamly.Prelude as Stream
110-- >>> import Streamly.Internal.Data.Stream.IsStream as Stream
111-- >>> import qualified Streamly.Data.Array as Array
112-- >>> import qualified Streamly.Data.Fold as Fold
113-- >>> import qualified Streamly.Internal.Data.Fold as Fold
114-- >>> import qualified Streamly.Data.Unfold as Unfold
116------------------------------------------------------------------------------
117-- Generation
118------------------------------------------------------------------------------
120-- Faster than fromEffect because there is no bind.
121--
122-- |
123-- @
124-- fromPure a = a \`cons` nil
125-- @
126--
127-- Create a singleton stream from a pure value.
128--
129-- The following holds in monadic streams, but not in Zip streams:
130--
131-- @
132-- fromPure = pure
133-- fromPure = fromEffect . pure
134-- @
135--
136-- In Zip applicative streams 'fromPure' is not the same as 'pure' because in that
137-- case 'pure' is equivalent to 'repeat' instead. 'fromPure' and 'pure' are
138-- equally efficient, in other cases 'fromPure' may be slightly more efficient
139-- than the other equivalent definitions.
140--
141-- /Since: 0.8.0 (Renamed yield to fromPure)/
142--
143{-# INLINE fromPure #-}
144fromPure :: IsStream t => a -> t m a
145fromPure = fromStream . K.fromPure
147-- | Same as 'fromPure'
148--
149-- @since 0.4.0
150{-# DEPRECATED yield "Please use fromPure instead." #-}
151{-# INLINE yield #-}
152yield :: IsStream t => a -> t m a
153yield = fromPure
155-- |
156-- @
157-- fromEffect m = m \`consM` nil
158-- @
159--
160-- Create a singleton stream from a monadic action.
161--
162-- @
163-- > Stream.toList $ Stream.fromEffect getLine
164-- hello
165-- ["hello"]
166-- @
167--
168-- /Since: 0.8.0 (Renamed yieldM to fromEffect)/
169--
170{-# INLINE fromEffect #-}
171fromEffect :: (Monad m, IsStream t) => m a -> t m a
172fromEffect = fromStream . K.fromEffect
174-- | Same as 'fromEffect'
175--
176-- @since 0.4.0
177{-# DEPRECATED yieldM "Please use fromEffect instead." #-}
178{-# INLINE yieldM #-}
179yieldM :: (Monad m, IsStream t) => m a -> t m a
180yieldM = fromEffect
181-- |
182-- >>> repeatM = fix . consM
183-- >>> repeatM = cycle1 . fromEffect
184--
185-- Generate a stream by repeatedly executing a monadic action forever.
186--
187-- >>> :{
188-- repeatAsync =
189-- Stream.repeatM (threadDelay 1000000 >> print 1)
190-- & Stream.take 10
191-- & Stream.fromAsync
192-- & Stream.drain
193-- :}
194--
195-- /Concurrent, infinite (do not use with 'fromParallel')/
196--
197-- @since 0.2.0
198{-# INLINE_EARLY repeatM #-}
199repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
200repeatM = K.repeatMWith IsStream.consM
202{-# RULES "repeatM serial" repeatM = repeatMSerial #-}
203{-# INLINE repeatMSerial #-}
204repeatMSerial :: MonadAsync m => m a -> SerialT m a
205repeatMSerial = fromStreamD . D.repeatM
207------------------------------------------------------------------------------
208-- Generation - Time related
209------------------------------------------------------------------------------
211-- | @timesWith g@ returns a stream of time value tuples. The first component
212-- of the tuple is an absolute time reference (epoch) denoting the start of the
213-- stream and the second component is a time relative to the reference.
214--
215-- The argument @g@ specifies the granularity of the relative time in seconds.
216-- A lower granularity clock gives higher precision but is more expensive in
217-- terms of CPU usage. Any granularity lower than 1 ms is treated as 1 ms.
218--
219-- >>> import Control.Concurrent (threadDelay)
220-- >>> import Streamly.Internal.Data.Stream.IsStream.Common as Stream (timesWith)
221-- >>> Stream.mapM_ (\x -> print x >> threadDelay 1000000) $ Stream.take 3 $ Stream.timesWith 0.01
222-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
223-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
224-- (AbsTime (TimeSpec {sec = ..., nsec = ...}),RelTime64 (NanoSecond64 ...))
225--
226-- Note: This API is not safe on 32-bit machines.
227--
228-- /Pre-release/
229--
230{-# INLINE timesWith #-}
231timesWith :: (IsStream t, MonadAsync m) => Double -> t m (AbsTime, RelTime64)
232timesWith g = fromStreamD $ D.timesWith g
234-- | @absTimesWith g@ returns a stream of absolute timestamps using a clock of
235-- granularity @g@ specified in seconds. A low granularity clock is more
236-- expensive in terms of CPU usage. Any granularity lower than 1 ms is treated
237-- as 1 ms.
238--
239-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ absTimesWith 0.01
240-- AbsTime (TimeSpec {sec = ..., nsec = ...})
241-- AbsTime (TimeSpec {sec = ..., nsec = ...})
242-- AbsTime (TimeSpec {sec = ..., nsec = ...})
243--
244-- Note: This API is not safe on 32-bit machines.
245--
246-- /Pre-release/
247--
248{-# INLINE absTimesWith #-}
249absTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
250 => Double -> t m AbsTime
251absTimesWith = fmap (uncurry addToAbsTime64) . timesWith
253-- | @relTimesWith g@ returns a stream of relative time values starting from 0,
254-- using a clock of granularity @g@ specified in seconds. A low granularity
255-- clock is more expensive in terms of CPU usage. Any granularity lower than 1
256-- ms is treated as 1 ms.
257--
258-- >>> Stream.mapM_ print $ Stream.delayPre 1 $ Stream.take 3 $ Stream.relTimesWith 0.01
259-- RelTime64 (NanoSecond64 ...)
260-- RelTime64 (NanoSecond64 ...)
261-- RelTime64 (NanoSecond64 ...)
262--
263-- Note: This API is not safe on 32-bit machines.
264--
265-- /Pre-release/
266--
267{-# INLINE relTimesWith #-}
268relTimesWith :: (IsStream t, MonadAsync m, Functor (t m))
269 => Double -> t m RelTime64
270relTimesWith = fmap snd . timesWith
272------------------------------------------------------------------------------
273-- Elimination - Running a Fold
274------------------------------------------------------------------------------
276-- | We can create higher order folds using 'foldContinue'. We can fold a
277-- number of streams to a given fold efficiently with full stream fusion. For
278-- example, to fold a list of streams on the same sum fold:
279--
280-- > concatFold = Prelude.foldl Stream.foldContinue Fold.sum
281--
282-- > fold f = Fold.extractM . Stream.foldContinue f
283--
284-- /Internal/
285{-# INLINE foldContinue #-}
286foldContinue :: Monad m => Fold m a b -> SerialT m a -> Fold m a b
287foldContinue f s = D.foldAddLazy f $ IsStream.toStreamD s
289-- | Fold a stream using the supplied left 'Fold' and reducing the resulting
290-- expression strictly at each step. The behavior is similar to 'foldl''. A
291-- 'Fold' can terminate early without consuming the full stream. See the
292-- documentation of individual 'Fold's for termination behavior.
293--
294-- >>> Stream.fold Fold.sum (Stream.enumerateFromTo 1 100)
295-- 5050
296--
297-- Folds never fail, therefore, they produce a default value even when no input
298-- is provided. It means we can always fold an empty stream and get a valid
299-- result. For example:
300--
301-- >>> Stream.fold Fold.sum Stream.nil
302-- 0
303--
304-- However, 'foldMany' on an empty stream results in an empty stream.
305-- Therefore, @Stream.fold f@ is not the same as @Stream.head . Stream.foldMany
306-- f@.
307--
308-- @fold f = Stream.parse (Parser.fromFold f)@
309--
310-- @since 0.7.0
311{-# INLINE fold #-}
312fold :: Monad m => Fold m a b -> SerialT m a -> m b
313fold fl strm = D.fold fl $ IsStream.toStreamD strm
315------------------------------------------------------------------------------
316-- Transformation
317------------------------------------------------------------------------------
319-- |
320-- @
321-- map = fmap
322-- @
323--
324-- Same as 'fmap'.
325--
326-- @
327-- > D.toList $ D.map (+1) $ D.fromList [1,2,3]
328-- [2,3,4]
329-- @
330--
331-- @since 0.4.0
332{-# INLINE map #-}
333map :: (IsStream t, Monad m) => (a -> b) -> t m a -> t m b
334map f = fromStreamD . D.map f . toStreamD
336-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
337-- that it provides an additional @done@ function to be applied on the
338-- accumulator when the stream stops. The result of @done@ is also emitted in
339-- the stream.
340--
341-- This function can be used to allocate a resource in the beginning of the
342-- scan and release it when the stream ends or to flush the internal state of
343-- the scan at the end.
344--
345-- /Pre-release/
346--
347{-# INLINE scanlMAfter' #-}
348scanlMAfter' :: (IsStream t, Monad m)
349 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
350scanlMAfter' step initial done stream =
351 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
353{-# INLINE postscanlMAfter' #-}
354postscanlMAfter' :: (IsStream t, Monad m)
355 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
356postscanlMAfter' step initial done stream =
357 fromStreamD $ D.postscanlMAfter' step initial done $ toStreamD stream
359-- XXX this needs to be concurrent
360-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
361--
362-- >>> postscanlM' f z xs = Stream.drop 1 $ Stream.scanlM' f z xs
363--
364-- /Since: 0.7.0/
365--
366-- /Since: 0.8.0 (signature change)/
367{-# INLINE postscanlM' #-}
368postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
369postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
371-- $smapM_Notes
372--
373-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
374-- a read-only environment. However, that would just be 'mapM'.
375--
376-- The initial action could be @m (s, Maybe b)@, and we can also add a final
377-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
378-- functionality and also to flush the state in the end like scanlMAfter'.
379-- We can also use it along with a fusible version of bracket to get
380-- scanlMAfter' like functionality. See issue #677.
381--
382-- This can be further generalized to a type similar to Fold/Parser, giving it
383-- filtering and parsing capability as well (this is in fact equivalent to
384-- parseMany):
385--
386-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
387--
389-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
390-- Hopefully, this is a better alternative to @scan@. Separation of state from
391-- the output makes it easier to think in terms of a shared state, and also
392-- makes it easier to keep the state fully strict and the output lazy.
393--
394-- See also: 'scanlM''
395--
396-- /Pre-release/
397--
398{-# INLINE smapM #-}
399smapM :: (IsStream t, Monad m) =>
400 (s -> a -> m (s, b))
401 -> m s
402 -> t m a
403 -> t m b
404smapM step initial stream =
405 -- XXX implement this directly instead of using scanlM'
406 -- Once we have postscanlM' with monadic initial we can use this code
407 -- let r = postscanlM'
408 -- (\(s, _) a -> step s a)
409 -- (fmap (,undefined) initial)
410 -- stream
411 let r = postscanlM'
412 (\(s, _) a -> step s a)
413 (fmap (,undefined) initial)
414 stream
415 in map snd r
417------------------------------------------------------------------------------
418-- Transformation - Trimming
419------------------------------------------------------------------------------
421-- | Take first 'n' elements from the stream and discard the rest.
422--
423-- @since 0.1.0
424{-# INLINE take #-}
425take :: (IsStream t, Monad m) => Int -> t m a -> t m a
426take n m = fromStreamD $ D.take n $ toStreamD
427 (maxYields (Just (fromIntegral n)) m)
429-- | End the stream as soon as the predicate fails on an element.
430--
431-- @since 0.1.0
432{-# INLINE takeWhile #-}
433takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
434takeWhile p m = fromStreamD $ D.takeWhile p $ toStreamD m
436{-# INLINE takeEndBy #-}
437takeEndBy :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
438takeEndBy p m = fromStreamD $ D.takeEndBy p $ toStreamD m
440-- | Discard first 'n' elements from the stream and take the rest.
441--
442-- @since 0.1.0
443{-# INLINE drop #-}
444drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
445drop n m = fromStreamD $ D.drop n $ toStreamD m
447------------------------------------------------------------------------------
448-- Searching
449------------------------------------------------------------------------------
451-- | Find all the indices where the element in the stream satisfies the given
452-- predicate.
453--
454-- > findIndices = fold Fold.findIndices
455--
456-- @since 0.5.0
457{-# INLINE findIndices #-}
458findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
459findIndices p m = fromStreamD $ D.findIndices p (toStreamD m)
461------------------------------------------------------------------------------
462-- Transformation by Inserting
463------------------------------------------------------------------------------
465-- intersperseM = intersperseMWith 1
467-- | Insert an effect and its output before consuming an element of a stream
468-- except the first one.
469--
470-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
471-- h.,e.,l.,l.,o"h,e,l,l,o"
472--
473-- Be careful about the order of effects. In the above example we used trace
474-- after the intersperse, if we use it before the intersperse the output would
475-- be he.l.l.o."h,e,l,l,o".
476--
477-- >>> Stream.toList $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.trace putChar $ Stream.fromList "hello"
478-- he.l.l.o."h,e,l,l,o"
479--
480-- @since 0.5.0
481{-# INLINE intersperseM #-}
482intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
483intersperseM m = fromStreamD . D.intersperseM m . toStreamD
485-- | Intersperse a monadic action into the input stream after every @n@
486-- seconds.
487--
488-- @
489-- > import Control.Concurrent (threadDelay)
490-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
491-- h,e,l,l,o
492-- @
493--
494-- /Pre-release/
495{-# INLINE interjectSuffix #-}
496interjectSuffix
497 :: (IsStream t, MonadAsync m)
498 => Double -> m a -> t m a -> t m a
499interjectSuffix n f xs = xs `parallelFst` repeatM timed
500 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
502------------------------------------------------------------------------------
503-- Transformation by Reordering
504------------------------------------------------------------------------------
506-- XXX Use a compact region list to temporarily store the list, in both reverse
507-- as well as in reverse'.
508--
509-- /Note:/ 'reverse'' is much faster than this, use that when performance
510-- matters.
511--
512-- | Returns the elements of the stream in reverse order. The stream must be
513-- finite. Note that this necessarily buffers the entire stream in memory.
514--
515-- >>> reverse = Stream.foldlT (flip Stream.cons) Stream.nil
516--
517-- /Since 0.7.0 (Monad m constraint)/
518--
519-- /Since: 0.1.1/
520{-# INLINE reverse #-}
521reverse :: (IsStream t, Monad m) => t m a -> t m a
522reverse s = fromStreamD $ D.reverse $ toStreamD s
524-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
525--
526-- /Pre-release/
527{-# INLINE reverse' #-}
528reverse' :: (IsStream t, MonadIO m, Unbox a) => t m a -> t m a
529-- reverse' s = fromStreamD $ D.reverse' $ toStreamD s
530reverse' =
531 fromStreamD
532 . A.flattenArraysRev -- unfoldMany A.readRev
533 . D.fromStreamK
534 . K.reverse
535 . D.toStreamK
536 . A.chunksOf defaultChunkSize
537 . toStreamD
539------------------------------------------------------------------------------
540-- Concurrent Transformations and Combining
541------------------------------------------------------------------------------
543-- | Make the stream producer and consumer run concurrently by introducing a
544-- buffer between them. The producer thread evaluates the input stream until
545-- the buffer fills, it terminates if the buffer is full and a worker thread is
546-- kicked off again to evaluate the remaining stream when there is space in the
547-- buffer. The consumer consumes the stream lazily from the buffer.
548--
549-- /Since: 0.2.0 (Streamly)/
550--
551-- @since 0.8.0
552--
553{-# INLINE_NORMAL mkAsync #-}
554mkAsync :: (IsStream t, MonadAsync m) => t m a -> t m a
555mkAsync = fromStreamD . Async.mkAsyncD . toStreamD
557-- Compare with mkAsync. mkAsync uses an Async style SVar whereas this uses a
558-- parallel style SVar for evaluation. Currently, parallel style cannot use
559-- rate control whereas Async style can use rate control. In async style SVar
560-- the worker thread terminates when the buffer is full whereas in Parallel
561-- style it blocks.
562--
563-- | Make the stream producer and consumer run concurrently by introducing a
564-- buffer between them. The producer thread evaluates the input stream until
565-- the buffer fills, it blocks if the buffer is full until there is space in
566-- the buffer. The consumer consumes the stream lazily from the buffer.
567--
568-- @mkParallel = IsStream.fromStreamD . mkParallelD . IsStream.toStreamD@
569--
570-- /Pre-release/
571--
572{-# INLINE_NORMAL mkParallel #-}
573mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
574mkParallel = fromStreamD . Par.mkParallelD . toStreamD
576-- | Like `parallel` but stops the output as soon as the first stream stops.
577--
578-- /Pre-release/
579{-# INLINE parallelFst #-}
580parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
581parallelFst m1 m2 = fromStream $ Par.parallelFstK (toStream m1) (toStream m2)
583------------------------------------------------------------------------------
584-- Combine streams and flatten
585------------------------------------------------------------------------------
587-- | Map a stream producing monadic function on each element of the stream
588-- and then flatten the results into a single stream. Since the stream
589-- generation function is monadic, unlike 'concatMap', it can produce an
590-- effect at the beginning of each iteration of the inner loop.
591--
592-- @since 0.6.0
593{-# INLINE concatMapM #-}
594concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
595concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
597-- | Map a stream producing function on each element of the stream and then
598-- flatten the results into a single stream.
599--
600-- >>> concatMap f = Stream.concatMapM (return . f)
601-- >>> concatMap f = Stream.concatMapWith Stream.serial f
602-- >>> concatMap f = Stream.concat . Stream.map f
603--
604-- @since 0.6.0
605{-# INLINE concatMap #-}
606concatMap ::(IsStream t, Monad m) => (a -> t m b) -> t m a -> t m b
607concatMap f m = fromStreamD $ D.concatMap (toStreamD . f) (toStreamD m)
609-- | Given a stream value in the underlying monad, lift and join the underlying
610-- monad with the stream monad.
611--
612-- >>> concatM = Stream.concat . Stream.fromEffect
613-- >>> concatM = Stream.concat . lift -- requires (MonadTrans t)
614-- >>> concatM = join . lift -- requires (MonadTrans t, Monad (t m))
615--
616-- See also: 'concat', 'sequence'
617--
618-- /Internal/
619--
620{-# INLINE concatM #-}
621concatM :: (IsStream t, Monad m) => m (t m a) -> t m a
622concatM generator = concatMapM (\() -> generator) (fromPure ())
624-- | Like 'foldMany' but appends empty fold output if the fold and stream
625-- termination aligns:
626--
627-- >>> f = Fold.take 2 Fold.sum
628-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList []
629-- [0]
630-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..9]
631-- [3,7,11,15,9]
632-- >>> Stream.toList $ Stream.foldManyPost f $ Stream.fromList [1..10]
633-- [3,7,11,15,19,0]
634--
635-- /Pre-release/
636--
637{-# INLINE foldManyPost #-}
638foldManyPost
639 :: (IsStream t, Monad m)
640 => Fold m a b
641 -> t m a
642 -> t m b
643foldManyPost f m = fromStreamD $ D.foldManyPost f (toStreamD m)
645------------------------------------------------------------------------------
646-- Split stream and fold
647------------------------------------------------------------------------------
649-- $
650-- > intercalate . splitOnSeq == id
651-- prop> (\f -> unsafePerformIO . Stream.toList . f . Stream.fromList) (Stream.intercalate Unfold.fromList " " . Stream.splitOnSeq (Array.fromList " ") Fold.toList) xs == xs
653-- | Like 'splitOn' but the separator is a sequence of elements instead of a
654-- single element.
655--
656-- For illustration, let's define a function that operates on pure lists:
657--
658-- >>> splitOnSeq' pat xs = Stream.toList $ Stream.splitOnSeq (Array.fromList pat) Fold.toList (Stream.fromList xs)
659--
660-- >>> splitOnSeq' "" "hello"
661-- ["h","e","l","l","o"]
662--
663-- >>> splitOnSeq' "hello" ""
664-- [""]
665--
666-- >>> splitOnSeq' "hello" "hello"
667-- ["",""]
668--
669-- >>> splitOnSeq' "x" "hello"
670-- ["hello"]
671--
672-- >>> splitOnSeq' "h" "hello"
673-- ["","ello"]
674--
675-- >>> splitOnSeq' "o" "hello"
676-- ["hell",""]
677--
678-- >>> splitOnSeq' "e" "hello"
679-- ["h","llo"]
680--
681-- >>> splitOnSeq' "l" "hello"
682-- ["he","","o"]
683--
684-- >>> splitOnSeq' "ll" "hello"
685-- ["he","o"]
686--
687-- 'splitOnSeq' is an inverse of 'intercalate'. The following law always holds:
688--
689-- > intercalate . splitOnSeq == id
690--
691-- The following law holds when the separator is non-empty and contains none of
692-- the elements present in the input lists:
693--
694-- > splitOnSeq . intercalate == id
695--
696-- >>> splitOnSeq pat f = Stream.foldManyPost (Fold.takeEndBySeq_ pat f)
697--
698-- /Pre-release/
700-- XXX We can use a polymorphic vector implemented by Array# to represent the
701-- sequence, that way we can avoid the Storable constraint. If we still need
702-- Storable Array for performance, we can use a separate splitOnArray API for
703-- that. We can also have an API where the sequence itself is a lazy stream, so
704-- that we can search files in files for example.
705{-# INLINE splitOnSeq #-}
706splitOnSeq
707 :: (IsStream t, MonadIO m, Storable a, Unbox a, Enum a, Eq a)
708 => Array a -> Fold m a b -> t m a -> t m b
709splitOnSeq patt f m =
710 IsStream.fromStreamD $ D.splitOnSeq patt f (IsStream.toStreamD m)
711-- XXX This may have a problem if the stream terminates and we start extracting
712-- the fold and then the fold terminates before consuming all the buffered
713-- input. We have no way to supply the buffered input back to the driver.
714-- splitOnSeq patt f =
715 -- foldManyPost (Fold.takeEndBySeq_ patt f)
717------------------------------------------------------------------------------
718-- Zipping
719------------------------------------------------------------------------------
721-- | Like 'zipWith' but using a monadic zipping function.
722--
723-- @since 0.4.0
724{-# INLINE zipWithM #-}
725zipWithM :: (IsStream t, Monad m) => (a -> b -> m c) -> t m a -> t m b -> t m c
726zipWithM f m1 m2 =
727 IsStream.fromStreamD
728 $ D.zipWithM f (IsStream.toStreamD m1) (IsStream.toStreamD m2)
730-- | Stream @a@ is evaluated first, followed by stream @b@, the resulting
731-- elements @a@ and @b@ are then zipped using the supplied zip function and the
732-- result @c@ is yielded to the consumer.
733--
734-- If stream @a@ or stream @b@ ends, the zipped stream ends. If stream @b@ ends
735-- first, the element @a@ from previous evaluation of stream @a@ is discarded.
736--
737-- @
738-- > D.toList $ D.zipWith (+) (D.fromList [1,2,3]) (D.fromList [4,5,6])
739-- [5,7,9]
740-- @
741--
742-- @since 0.1.0
743{-# INLINE zipWith #-}
744zipWith :: (IsStream t, Monad m) => (a -> b -> c) -> t m a -> t m b -> t m c
745zipWith f m1 m2 =
746 IsStream.fromStreamD
747 $ D.zipWith f (IsStream.toStreamD m1) (IsStream.toStreamD m2)