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