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