on d2aaef0 help sign in
722 lines 25 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3-- |
4-- Module : Streamly.Internal.Data.Stream.IsStream.Common
5-- Copyright : (c) 2017 Composewell Technologies
6-- License : BSD-3-Clause
7-- Maintainer : streamly@composewell.com
8-- Stability : experimental
9-- Portability : GHC
10--
11-- Bottom level IsStream module that can be used by all other upper level
12-- IsStream modules.
14module Streamly.Internal.Data.Stream.IsStream.Common
15 (
16 -- * Generation
17 fromPure
18 , fromEffect
19 , repeatM
20 , timesWith
21 , absTimesWith
22 , relTimesWith
24 -- * Elimination
25 , foldContinue
26 , Stream.fold
27 , Stream.foldBreak
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 qualified Foreign.Storable as Storable (Storable)
73import Streamly.Internal.Control.Concurrent (MonadAsync)
74import Streamly.Internal.Data.Array.Unboxed.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, fromStreamS, toStreamS)
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 (Unboxed)
84import qualified Streamly.Internal.Data.Array.Unboxed.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
89import qualified Streamly.Internal.Data.Stream.StreamD as D
90#ifdef USE_STREAMK_ONLY
91import qualified Streamly.Internal.Data.Stream.StreamK as S
92#else
93import qualified Streamly.Internal.Data.Stream.StreamD as S
94#endif
95import qualified Streamly.Internal.Data.Stream as Stream
97import Prelude hiding (take, takeWhile, drop, reverse, concatMap, map, zipWith)
99--
100-- $setup
101-- >>> :m
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.Unboxed 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 = fromStreamS . S.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.times 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.finish . 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.foldContinue f $ IsStream.toStreamD s
289------------------------------------------------------------------------------
290-- Transformation
291------------------------------------------------------------------------------
293-- |
294-- @
295-- map = fmap
296-- @
297--
298-- Same as 'fmap'.
299--
300-- @
301-- > S.toList $ S.map (+1) $ S.fromList [1,2,3]
302-- [2,3,4]
303-- @
304--
305-- @since 0.4.0
306{-# INLINE map #-}
307map :: (IsStream t, Monad m) => (a -> b) -> t m a -> t m b
308map f = fromStreamD . D.map f . toStreamD
310-- | @scanlMAfter' accumulate initial done stream@ is like 'scanlM'' except
311-- that it provides an additional @done@ function to be applied on the
312-- accumulator when the stream stops. The result of @done@ is also emitted in
313-- the stream.
314--
315-- This function can be used to allocate a resource in the beginning of the
316-- scan and release it when the stream ends or to flush the internal state of
317-- the scan at the end.
318--
319-- /Pre-release/
320--
321{-# INLINE scanlMAfter' #-}
322scanlMAfter' :: (IsStream t, Monad m)
323 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
324scanlMAfter' step initial done stream =
325 fromStreamD $ D.scanlMAfter' step initial done $ toStreamD stream
327{-# INLINE postscanlMAfter' #-}
328postscanlMAfter' :: (IsStream t, Monad m)
329 => (b -> a -> m b) -> m b -> (b -> m b) -> t m a -> t m b
330postscanlMAfter' step initial done stream =
331 fromStreamD $ D.postscanlMAfter' step initial done $ toStreamD stream
333-- XXX this needs to be concurrent
334-- | Like 'postscanl'' but with a monadic step function and a monadic seed.
335--
336-- >>> postscanlM' f z xs = Stream.drop 1 $ Stream.scanlM' f z xs
337--
338-- /Since: 0.7.0/
339--
340-- /Since: 0.8.0 (signature change)/
341{-# INLINE postscanlM' #-}
342postscanlM' :: (IsStream t, Monad m) => (b -> a -> m b) -> m b -> t m a -> t m b
343postscanlM' step z m = fromStreamD $ D.postscanlM' step z $ toStreamD m
345-- $smapM_Notes
346--
347-- The stateful step function can be simplified to @(s -> a -> m b)@ to provide
348-- a read-only environment. However, that would just be 'mapM'.
349--
350-- The initial action could be @m (s, Maybe b)@, and we can also add a final
351-- action @s -> m (Maybe b)@. This can be used to get pre/post scan like
352-- functionality and also to flush the state in the end like scanlMAfter'.
353-- We can also use it along with a fusible version of bracket to get
354-- scanlMAfter' like functionality. See issue #677.
355--
356-- This can be further generalized to a type similar to Fold/Parser, giving it
357-- filtering and parsing capability as well (this is in fact equivalent to
358-- parseMany):
359--
360-- smapM :: (s -> a -> m (Step s b)) -> m s -> t m a -> t m b
361--
363-- | A stateful 'mapM', equivalent to a left scan, more like mapAccumL.
364-- Hopefully, this is a better alternative to @scan@. Separation of state from
365-- the output makes it easier to think in terms of a shared state, and also
366-- makes it easier to keep the state fully strict and the output lazy.
367--
368-- See also: 'scanlM''
369--
370-- /Pre-release/
371--
372{-# INLINE smapM #-}
373smapM :: (IsStream t, Monad m) =>
374 (s -> a -> m (s, b))
375 -> m s
376 -> t m a
377 -> t m b
378smapM step initial stream =
379 -- XXX implement this directly instead of using scanlM'
380 -- Once we have postscanlM' with monadic initial we can use this code
381 -- let r = postscanlM'
382 -- (\(s, _) a -> step s a)
383 -- (fmap (,undefined) initial)
384 -- stream
385 let r = postscanlM'
386 (\(s, _) a -> step s a)
387 (fmap (,undefined) initial)
388 stream
389 in map snd r
391------------------------------------------------------------------------------
392-- Transformation - Trimming
393------------------------------------------------------------------------------
395-- | Take first 'n' elements from the stream and discard the rest.
396--
397-- @since 0.1.0
398{-# INLINE take #-}
399take :: (IsStream t, Monad m) => Int -> t m a -> t m a
400take n m = fromStreamS $ S.take n $ toStreamS
401 (maxYields (Just (fromIntegral n)) m)
403-- | End the stream as soon as the predicate fails on an element.
404--
405-- @since 0.1.0
406{-# INLINE takeWhile #-}
407takeWhile :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
408takeWhile p m = fromStreamS $ S.takeWhile p $ toStreamS m
410{-# INLINE takeEndBy #-}
411takeEndBy :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m a
412takeEndBy p m = fromStreamD $ D.takeEndBy p $ toStreamD m
414-- | Discard first 'n' elements from the stream and take the rest.
415--
416-- @since 0.1.0
417{-# INLINE drop #-}
418drop :: (IsStream t, Monad m) => Int -> t m a -> t m a
419drop n m = fromStreamS $ S.drop n $ toStreamS m
421------------------------------------------------------------------------------
422-- Searching
423------------------------------------------------------------------------------
425-- | Find all the indices where the element in the stream satisfies the given
426-- predicate.
427--
428-- > findIndices = fold Fold.findIndices
429--
430-- @since 0.5.0
431{-# INLINE findIndices #-}
432findIndices :: (IsStream t, Monad m) => (a -> Bool) -> t m a -> t m Int
433findIndices p m = fromStreamS $ S.findIndices p (toStreamS m)
435------------------------------------------------------------------------------
436-- Transformation by Inserting
437------------------------------------------------------------------------------
439-- intersperseM = intersperseBySpan 1
441-- | Insert an effect and its output before consuming an element of a stream
442-- except the first one.
443--
444-- >>> Stream.toList $ Stream.trace putChar $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.fromList "hello"
445-- h.,e.,l.,l.,o"h,e,l,l,o"
446--
447-- Be careful about the order of effects. In the above example we used trace
448-- after the intersperse, if we use it before the intersperse the output would
449-- be he.l.l.o."h,e,l,l,o".
450--
451-- >>> Stream.toList $ Stream.intersperseM (putChar '.' >> return ',') $ Stream.trace putChar $ Stream.fromList "hello"
452-- he.l.l.o."h,e,l,l,o"
453--
454-- @since 0.5.0
455{-# INLINE intersperseM #-}
456intersperseM :: (IsStream t, MonadAsync m) => m a -> t m a -> t m a
457intersperseM m = fromStreamS . S.intersperseM m . toStreamS
459-- | Intersperse a monadic action into the input stream after every @n@
460-- seconds.
461--
462-- @
463-- > import Control.Concurrent (threadDelay)
464-- > Stream.drain $ Stream.interjectSuffix 1 (putChar ',') $ Stream.mapM (\x -> threadDelay 1000000 >> putChar x) $ Stream.fromList "hello"
465-- h,e,l,l,o
466-- @
467--
468-- /Pre-release/
469{-# INLINE interjectSuffix #-}
470interjectSuffix
471 :: (IsStream t, MonadAsync m)
472 => Double -> m a -> t m a -> t m a
473interjectSuffix n f xs = xs `parallelFst` repeatM timed
474 where timed = liftIO (threadDelay (round $ n * 1000000)) >> f
476------------------------------------------------------------------------------
477-- Transformation by Reordering
478------------------------------------------------------------------------------
480-- XXX Use a compact region list to temporarily store the list, in both reverse
481-- as well as in reverse'.
482--
483-- /Note:/ 'reverse'' is much faster than this, use that when performance
484-- matters.
485--
486-- | Returns the elements of the stream in reverse order. The stream must be
487-- finite. Note that this necessarily buffers the entire stream in memory.
488--
489-- >>> reverse = Stream.foldlT (flip Stream.cons) Stream.nil
490--
491-- /Since 0.7.0 (Monad m constraint)/
492--
493-- /Since: 0.1.1/
494{-# INLINE reverse #-}
495reverse :: (IsStream t, Monad m) => t m a -> t m a
496reverse s = fromStreamS $ S.reverse $ toStreamS s
498-- | Like 'reverse' but several times faster, requires a 'Storable' instance.
499--
500-- /Pre-release/
501{-# INLINE reverse' #-}
502reverse' :: (IsStream t, MonadIO m, Unboxed a) => t m a -> t m a
503-- reverse' s = fromStreamD $ D.reverse' $ toStreamD s
504reverse' =
505 fromStreamD
506 . A.flattenArraysRev -- unfoldMany A.readRev
507 . D.fromStreamK
508 . K.reverse
509 . D.toStreamK
510 . A.arraysOf defaultChunkSize
511 . toStreamD
513------------------------------------------------------------------------------
514-- Concurrent Transformations and Combining
515------------------------------------------------------------------------------
517-- | Make the stream producer and consumer run concurrently by introducing a
518-- buffer between them. The producer thread evaluates the input stream until
519-- the buffer fills, it terminates if the buffer is full and a worker thread is
520-- kicked off again to evaluate the remaining stream when there is space in the
521-- buffer. The consumer consumes the stream lazily from the buffer.
522--
523-- /Since: 0.2.0 (Streamly)/
524--
525-- @since 0.8.0
526--
527{-# INLINE_NORMAL mkAsync #-}
528mkAsync :: (IsStream t, MonadAsync m) => t m a -> t m a
529mkAsync = fromStreamD . Async.mkAsyncD . toStreamD
531-- Compare with mkAsync. mkAsync uses an Async style SVar whereas this uses a
532-- parallel style SVar for evaluation. Currently, parallel style cannot use
533-- rate control whereas Async style can use rate control. In async style SVar
534-- the worker thread terminates when the buffer is full whereas in Parallel
535-- style it blocks.
536--
537-- | Make the stream producer and consumer run concurrently by introducing a
538-- buffer between them. The producer thread evaluates the input stream until
539-- the buffer fills, it blocks if the buffer is full until there is space in
540-- the buffer. The consumer consumes the stream lazily from the buffer.
541--
542-- @mkParallel = IsStream.fromStreamD . mkParallelD . IsStream.toStreamD@
543--
544-- /Pre-release/
545--
546{-# INLINE_NORMAL mkParallel #-}
547mkParallel :: (IsStream t, MonadAsync m) => t m a -> t m a
548mkParallel = fromStreamD . Par.mkParallelD . toStreamD
550-- | Like `parallel` but stops the output as soon as the first stream stops.
551--
552-- /Pre-release/
553{-# INLINE parallelFst #-}
554parallelFst :: (IsStream t, MonadAsync m) => t m a -> t m a -> t m a
555parallelFst m1 m2 = fromStream $ Par.parallelFstK (toStream m1) (toStream m2)
557------------------------------------------------------------------------------
558-- Combine streams and flatten
559------------------------------------------------------------------------------
561-- | Map a stream producing monadic function on each element of the stream
562-- and then flatten the results into a single stream. Since the stream
563-- generation function is monadic, unlike 'concatMap', it can produce an
564-- effect at the beginning of each iteration of the inner loop.
565--
566-- @since 0.6.0
567{-# INLINE concatMapM #-}
568concatMapM :: (IsStream t, Monad m) => (a -> m (t m b)) -> t m a -> t m b
569concatMapM f m = fromStreamD $ D.concatMapM (fmap toStreamD . f) (toStreamD m)
571-- | Map a stream producing function on each element of the stream and then
572-- flatten the results into a single stream.
573--
574-- >>> concatMap f = Stream.concatMapM (return . f)
575-- >>> concatMap f = Stream.concatMapWith Stream.serial f
576-- >>> concatMap f = Stream.concat . Stream.map f
577-- >>> concatMap f = Stream.unfoldMany (Unfold.lmap f Unfold.fromStream)
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, Storable.Storable a, Unboxed 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.fromStreamS
703 $ S.zipWithM f (IsStream.toStreamS m1) (IsStream.toStreamS 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-- > S.toList $ S.zipWith (+) (S.fromList [1,2,3]) (S.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.fromStreamS
722 $ S.zipWith f (IsStream.toStreamS m1) (IsStream.toStreamS m2)