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