on 796bb22 help sign in
streamly/src/Streamly/Prelude.hs
1238 lines 43 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Prelude
7-- Copyright : (c) 2017 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
12-- Portability : GHC
13--
14-- To run examples in this module:
15--
16-- >>> import qualified Streamly.Data.Fold as Fold
17-- >>> import qualified Streamly.Prelude as Stream
18--
19-- We will add some more imports in the examples as needed.
20--
21-- For effectful streams we will use the following IO action that blocks for
22-- @n@ seconds:
23--
24-- >>> import Control.Concurrent (threadDelay)
25-- >>> :{
26-- delay n = do
27-- threadDelay (n * 1000000) -- sleep for n seconds
28-- putStrLn (show n ++ " sec") -- print "n sec"
29-- return n -- IO Int
30-- :}
31--
32-- >>> delay 1
33-- 1 sec
34-- 1
35--
36-- = Overview
37--
38-- Streamly is a framework for modular data flow based programming and
39-- declarative concurrency. Powerful stream fusion framework in streamly
40-- allows high performance combinatorial programming even when using byte level
41-- streams. Streamly API is similar to Haskell lists.
42--
43-- The basic stream type is 'SerialT'. The type @SerialT IO a@ is an effectful
44-- equivalent of a list @[a]@ using the IO monad. Streams can be constructed
45-- like lists, except that they use 'nil' instead of '[]' and 'cons' instead of
46-- ':'.
47--
48-- `cons` constructs a pure stream which is more or less the same as a list:
49--
50-- >>> import Streamly.Prelude (SerialT, cons, consM, nil)
51-- >>> stream = 1 `cons` 2 `cons` nil :: SerialT IO Int
52-- >>> Stream.toList stream -- IO [Int]
53-- [1,2]
54--
55-- 'consM' constructs a stream from effectful actions:
56--
57-- >>> stream = delay 1 `consM` delay 2 `consM` nil
58-- >>> Stream.toList stream
59-- 1 sec
60-- 2 sec
61-- [1,2]
62--
63-- == Console Echo Program
64--
65-- In the following example, 'repeatM' generates an infinite stream of 'String'
66-- by repeatedly performing the 'getLine' IO action. 'mapM' then applies
67-- 'putStrLn' on each element in the stream converting it to stream of '()'.
68-- Finally, 'drain' folds the stream to IO discarding the () values, thus
69-- producing only effects.
70--
71-- >>> import Data.Function ((&))
72--
73-- @
74-- > :{
75-- Stream.repeatM getLine -- SerialT IO String
76-- & Stream.mapM putStrLn -- SerialT IO ()
77-- & Stream.drain -- IO ()
78-- :}
79-- @
80--
81-- This is a console echo program. It is an example of a declarative loop
82-- written using streaming combinators. Compare it with an imperative @while@
83-- loop.
84--
85-- Hopefully, this gives you an idea how we can program declaratively by
86-- representing loops using streams. In this module, you can find all
87-- "Data.List" like functions and many more powerful combinators to perform
88-- common programming tasks. Also see "Streamly.Internal.Data.Stream.IsStream"
89-- module for many more @Pre-release@ combinators. See the
90-- <https://github.com/composewell/streamly-examples> repository for many more
91-- real world examples of stream programming.
92--
93-- == Polymorphic Combinators
94--
95-- Streamly has several stream types, 'SerialT' is one type of stream with
96-- serial execution of actions, 'AsyncT' is another with concurrent execution.
97-- The combinators in this module are polymorphic in stream type. For example,
98--
99-- @
100-- repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
101-- @
102--
103-- @t@ is the stream type, @m@ is the underlying 'Monad' of the stream (e.g.
104-- IO) and @a@ is the type of elements in the stream (e.g. Int).
105--
106-- Stream elimination combinators accept a 'SerialT' type instead of a
107-- polymorphic type to force a concrete monomorphic type by default, reducing
108-- type errors. That's why in the console echo example above the stream type is
109-- 'SerialT'.
110--
111-- @
112-- drain :: Monad m => SerialT m a -> m ()
113-- @
114--
115-- We can force a certain stream type in polymorphic code by using "Stream Type
116-- Adaptors". For example, to force 'AsyncT':
117--
118-- >>> Stream.drain $ Stream.asyncly $ Stream.replicateM 10 $ delay 1
119-- ...
120--
121-- == Combining two streams
122--
123-- Two streams can be combined to form a single stream in various interesting
124-- ways. 'serial' (append), 'wSerial' (interleave), 'ahead' (concurrent,
125-- ordered append), 'async' (lazy concurrent, unordered append) , 'wAsync'
126-- (lazy concurrent, unordered interleave), 'parallel' (strict concurrent
127-- merge), 'zipWith', 'zipAsyncWith' (concurrent zip), 'mergeBy',
128-- 'mergeAsyncBy' (concurrent merge) are some ways of combining two streams.
129--
130-- For example, the `parallel` combinator schedules both the streams
131-- concurrently.
132--
133-- >>> stream1 = Stream.fromListM [delay 3, delay 4]
134-- >>> stream2 = Stream.fromListM [delay 1, delay 2]
135-- >>> Stream.toList $ stream1 `parallel` stream2
136-- ...
137--
138-- We can chain the operations to combine more than two streams:
139--
140-- >>> stream3 = Stream.fromListM [delay 1, delay 2]
141-- >>> Stream.toList $ stream1 `parallel` stream2 `parallel` stream3
142-- ...
143--
144-- Concurrent generation ('consM') and concurrent merging of streams is the
145-- fundamental basis of all concurrency in streamly.
146--
147-- == Combining many streams
148--
149-- The 'concatMapWith' combinator can be used to generalize the two stream
150-- combining combinators to @n@ streams. For example, we can use
151-- @concatMapWith parallel@ to read concurrently from all incoming network
152-- connections and combine the input streams into a single output stream:
153--
154-- @
155-- import qualified Streamly.Network.Inet.TCP as TCP
156-- import qualified Streamly.Network.Socket as Socket
157--
158-- Stream.unfold TCP.acceptOnPort 8090
159-- & Stream.concatMapWith Stream.parallel (Stream.unfold Socket.read)
160-- @
161--
162-- See the @streamly-examples@ repository for a full working example.
163--
164-- == Concurrent Nested Loops
165--
166-- The Monad instance of 'SerialT' is an example of nested looping. It is in
167-- fact a list transformer. Different stream types provide different variants
168-- of nested looping. For example, the 'Monad' instance of 'ParallelT' uses
169-- @concatMapWith parallel@ as its bind operation. Therefore, each iteration of
170-- the loop for 'ParallelT' stream can run concurrently. See the documentation
171-- for individual stream types for the specific execution behavior of the
172-- stream as well as the behavior of 'Semigroup' and 'Monad' instances.
173--
174-- == Stream Types
175--
176-- Streamly has several stream types. These types differ in three fundamental
177-- operations, 'consM' ('IsStream' instance), '<>' ('Semigroup' instance) and
178-- '>>=' ('Monad' instance). Below we will see how 'consM' behaves for
179-- 'SerialT', 'AsyncT' and 'AheadT' stream types.
180--
181-- 'SerialT' executes actions serially, so the total delay in the following
182-- example is @2 + 1 = 3@ seconds:
183--
184-- >>> stream = delay 2 `consM` delay 1 `consM` nil
185-- >>> Stream.toList stream -- IO [Int]
186-- 2 sec
187-- 1 sec
188-- [2,1]
189--
190-- 'AsyncT' executes the actions concurrently, so the total delay is @max 2 1 =
191-- 2@ seconds:
192--
193-- >>> Stream.toList $ Stream.asyncly stream -- IO [Int]
194-- 1 sec
195-- 2 sec
196-- [1,2]
197--
198-- 'AsyncT' produces the results in the order in which execution finishes.
199-- Notice the order of elements in the list above, it is not the same as the
200-- order of actions in the stream.
201--
202-- 'AheadT' is similar to 'AsyncT' but the order of results is the same as the
203-- order of actions, even though they execute concurrently:
204--
205-- >>> Stream.toList $ Stream.aheadly stream -- IO [Int]
206-- 1 sec
207-- 2 sec
208-- [2,1]
209--
210-- == Semigroup Instance
211--
212-- Earlier we distinguished stream types based on the execution behavior of
213-- actions within a stream. Stream types are also distinguished based on how
214-- actions from different streams are scheduled for execution when two streams
215-- are combined together.
216--
217-- For example, both 'SerialT' and 'WSerialT' execute actions within the stream
218-- serially, however, they differ in how actions from individual streams are
219-- executed when two streams are combined with '<>' (the 'Semigroup' instance).
220--
221-- For 'SerialT', '<>' has an appending behavior i.e. it executes the actions
222-- from the second stream after executing actions from the first stream:
223--
224-- >>> stream1 = Stream.fromListM [delay 1, delay 2]
225-- >>> stream2 = Stream.fromListM [delay 3, delay 4]
226-- >>> Stream.toList $ stream1 <> stream2
227-- 1 sec
228-- 2 sec
229-- 3 sec
230-- 4 sec
231-- [1,2,3,4]
232--
233-- For 'WSerialT', '<>' has an interleaving behavior i.e. it executes one
234-- action from the first stream and then one action from the second stream and
235-- so on:
236--
237-- >>> Stream.toList $ Stream.wSerially $ stream1 <> stream2
238-- 1 sec
239-- 3 sec
240-- 2 sec
241-- 4 sec
242-- [1,3,2,4]
243--
244-- The '<>' operation of 'SerialT' and 'WSerialT' is the same as 'serial' and
245-- 'wSerial' respectively. The 'serial' combinator combines two streams of any
246-- type in the same way as a serial stream combines.
247--
248-- == Concurrent Combinators
249--
250-- Like 'consM', there are several other stream generation operations whose
251-- execution behavior depends on the stream type, they all follow behavior
252-- similar to 'consM'.
253--
254-- By default, folds like 'drain' force the stream type to be 'SerialT', so
255-- 'replicateM' in the following code runs serially, and takes 10 seconds:
256--
257-- >>> Stream.drain $ Stream.replicateM 10 $ delay 1
258-- ...
259--
260-- We can use the 'asyncly' combinator to force the argument stream to be of
261-- 'AsyncT' type, 'replicateM' in the following example executes the replicated
262-- actions concurrently, thus taking only 1 second:
263--
264-- >>> Stream.drain $ Stream.asyncly $ Stream.replicateM 10 $ delay 1
265-- ...
266--
267-- We can use 'mapM' to map an action concurrently:
268--
269-- >>> f x = delay 1 >> return (x + 1)
270-- >>> Stream.toList $ Stream.aheadly $ Stream.mapM f $ Stream.fromList [1..3]
271-- ...
272-- [2,3,4]
273--
274-- 'aheadly' forces mapM to happen in 'AheadT' style, thus all three actions
275-- take only one second even though each individual action blocks for a second.
276--
277-- See the documentation of individual combinators to check if it is concurrent
278-- or not. The concurrent combinators necessarily have a @MonadAsync m@
279-- constraint. However, a @MonadAsync m@ constraint does not necessarily mean
280-- that the combinator is concurrent.
281--
282-- == Automatic Concurrency Control
283--
284-- 'SerialT' (and 'WSerialT') runs all tasks serially whereas 'ParallelT' runs
285-- all tasks concurrently i.e. one thread per task. The stream types 'AsyncT',
286-- 'WAsyncT', and 'AheadT' provide demand driven concurrency. It means that
287-- based on the rate at which the consumer is consuming the stream, it
288-- maintains the optimal number of threads to increase or decrease parallelism.
289--
290-- However, the programmer can control the maximum number of threads using
291-- 'maxThreads'. It provides an upper bound on the concurrent IO requests or
292-- CPU cores that can be used. 'maxBuffer' limits the number of evaluated
293-- stream elements that we can buffer. See the "Concurrency Control" section
294-- for details.
295--
296-- == Caveats
297--
298-- When we use combinators like 'asyncly' on a piece of code, all combinators
299-- inside the argument of asyncly become concurrent which is often counter
300-- productive. Therefore, we recommend that in a pipeline, you identify the
301-- combinators that you really want to be concurrent and add a 'serially' after
302-- those combinators so that the code following the combinator remains serial:
303--
304-- @
305-- Stream.asyncly $ ... concurrent combinator here ... $ Stream.serially $ ...
306-- @
307--
308-- == Conventions
309--
310-- Functions with the suffix @M@ are general functions that work on monadic
311-- arguments. The corresponding functions without the suffix @M@ work on pure
312-- arguments and can in general be derived from their monadic versions but are
313-- provided for convenience and for consistency with other pure APIs in the
314-- @base@ package.
315--
316-- In many cases, short definitions of the combinators are provided in the
317-- documentation for illustration. The actual implementation may differ for
318-- performance reasons.
320module Streamly.Prelude
321 (
322 -- * Construction
323 -- | Functions ending in the general shape @b -> t m a@
325 -- ** Primitives
326 -- | Primitives to construct a stream from pure values or monadic actions.
327 -- All other stream construction and generation combinators described later
328 -- can be expressed in terms of these primitives. However, the special
329 -- versions provided in this module can be much more efficient in most
330 -- cases. Users can create custom combinators using these primitives.
332 nil
333 , cons
334 , (.:)
336 , consM
337 , (|:)
339 -- ** Unfolding
340 -- | Generalized way of generating a stream efficiently.
341 , unfold
342 , unfoldr
343 , unfoldrM
345 -- ** From Values
346 -- | Generate a monadic stream from a seed value or values.
347 , yield
348 , yieldM
349 , repeat
350 , repeatM
351 , replicate
352 , replicateM
354 -- Note: Using enumeration functions e.g. 'Prelude.enumFromThen' turns out
355 -- to be slightly faster than the idioms like @[from, then..]@.
356 --
357 -- ** Enumeration
358 -- | We can use the 'Enum' type class to enumerate a type producing a list
359 -- and then convert it to a stream:
360 --
361 -- @
362 -- 'fromList' $ 'Prelude.enumFromThen' from then
363 -- @
364 --
365 -- However, this is not particularly efficient.
366 -- The 'Enumerable' type class provides corresponding functions that
367 -- generate a stream instead of a list, efficiently.
369 , Enumerable (..)
370 , enumerate
371 , enumerateTo
373 -- ** Iteration
374 , iterate
375 , iterateM
377 -- ** From Generators
378 -- | Generate a monadic stream from a seed value and a generator function.
379 , fromIndices
380 , fromIndicesM
382 -- ** From Containers
383 -- | Convert an input structure, container or source into a stream. All of
384 -- these can be expressed in terms of primitives.
385 , fromList
386 , fromListM
387 , fromFoldable
388 , fromFoldableM
390 -- * Elimination
391 -- | Functions ending in the general shape @t m a -> m b@
393 -- ** Running a 'Fold'
394 -- $runningfolds
396 , fold
397 , foldMany
399 -- ** Deconstruction
400 -- | Functions ending in the general shape @t m a -> m (b, t m a)@
402 , uncons
403 , tail
404 , init
406 -- ** General Folds
407-- | In imperative terms a fold can be considered as a loop over the stream
408-- that reduces the stream to a single value.
409-- Left and right folds both use a fold function @f@ and an identity element
410-- @z@ (@zero@) to deconstruct a recursive data structure and reconstruct a
411-- new data structure. The new structure may be a recursive construction (a
412-- container) or a non-recursive single value reduction of the original
413-- structure.
414--
415-- Both right and left folds are mathematical duals of each other, they are
416-- functionally equivalent. Operationally, a left fold on a left associated
417-- structure behaves exactly in the same way as a right fold on a right
418-- associated structure. Similarly, a left fold on a right associated structure
419-- behaves in the same way as a right fold on a left associated structure.
420-- However, the behavior of a right fold on a right associated structure is
421-- operationally different (even though functionally equivalent) than a left
422-- fold on the same structure.
423--
424-- On right associated structures like Haskell @cons@ lists or Streamly
425-- streams, a lazy right fold is naturally suitable for lazy recursive
426-- reconstruction of a new structure, while a strict left fold is naturally
427-- suitable for efficient reduction. In right folds control is in the hand of
428-- the @puller@ whereas in left folds the control is in the hand of the
429-- @pusher@.
430--
431-- The behavior of right and left folds are described in detail in the
432-- individual fold's documentation. To illustrate the two folds for right
433-- associated @cons@ lists:
434--
435-- > foldr :: (a -> b -> b) -> b -> [a] -> b
436-- > foldr f z [] = z
437-- > foldr f z (x:xs) = x `f` foldr f z xs
438-- >
439-- > foldl :: (b -> a -> b) -> b -> [a] -> b
440-- > foldl f z [] = z
441-- > foldl f z (x:xs) = foldl f (z `f` x) xs
442--
443-- @foldr@ is conceptually equivalent to:
444--
445-- > foldr f z [] = z
446-- > foldr f z [x] = f x z
447-- > foldr f z xs = foldr f (foldr f z (tail xs)) [head xs]
448--
449-- @foldl@ is conceptually equivalent to:
450--
451-- > foldl f z [] = z
452-- > foldl f z [x] = f z x
453-- > foldl f z xs = foldl f (foldl f z (init xs)) [last xs]
454--
455-- Left and right folds are duals of each other.
456--
457-- @
458-- foldr f z xs = foldl (flip f) z (reverse xs)
459-- foldl f z xs = foldr (flip f) z (reverse xs)
460-- @
461--
462-- More generally:
463--
464-- @
465-- foldr f z xs = foldl g id xs z where g k x = k . f x
466-- foldl f z xs = foldr g id xs z where g x k = k . flip f x
467-- @
468--
470-- As a general rule, foldr cannot have state and foldl cannot have control.
472-- NOTE: Folds are inherently serial as each step needs to use the result of
473-- the previous step. However, it is possible to fold parts of the stream in
474-- parallel and then combine the results using a monoid.
476 -- *** Right Folds
477 -- $rightfolds
478 , foldrM
479 , foldr
481 -- *** Left Folds
482 -- $leftfolds
483 , foldl'
484 , foldl1'
485 , foldlM'
487 -- ** Specific Folds
488 -- *** Full Folds
489 -- | Folds that are guaranteed to evaluate the whole stream.
491 -- -- ** To Summary (Full Folds)
492 -- -- | Folds that summarize the stream to a single value.
493 , drain
494 , last
495 , length
496 , sum
497 , product
499 -- -- ** To Summary (Maybe) (Full Folds)
500 -- -- | Folds that summarize a non-empty stream to a 'Just' value and return
501 -- 'Nothing' for an empty stream.
502 , maximumBy
503 , maximum
504 , minimumBy
505 , minimum
506 , the
508 -- *** Partial Folds
509 -- | Folds that may terminate before evaluating the whole stream. These
510 -- folds strictly evaluate the stream until the result is determined.
512 -- -- ** To Elements (Partial Folds)
513 , drainN
514 , drainWhile
516 -- -- | Folds that extract selected elements of a stream or their properties.
517 , (!!)
518 , head
519 , findM
520 , find
521 , lookup
522 , findIndex
523 , elemIndex
525 -- -- ** To Boolean (Partial Folds)
526 -- -- | Folds that summarize the stream to a boolean value.
527 , null
528 , elem
529 , notElem
530 , all
531 , any
532 , and
533 , or
535 -- *** To Containers
536 -- | Convert a stream into a container holding all the values.
537 , toList
539 -- ** Folding Concurrently
540 , (|$.)
541 , (|&.)
543 -- ** Multi-Stream folds
544 , eqBy
545 , cmpBy
546 , isPrefixOf
547 , isSubsequenceOf
549 -- trimming sequences
550 , stripPrefix
552 -- * Parallel Function Application
553 -- $application
554 , (|$)
555 , (|&)
557 -- * Transformation
559 -- ** Mapping
560 -- | In imperative terms a map operation can be considered as a loop over
561 -- the stream that transforms the stream into another stream by performing
562 -- an operation on each element of the stream.
563 --
564 -- 'map' is the least powerful transformation operation with strictest
565 -- guarantees. A map, (1) is a stateless loop which means that no state is
566 -- allowed to be carried from one iteration to another, therefore,
567 -- operations on different elements are guaranteed to not affect each
568 -- other, (2) is a strictly one-to-one transformation of stream elements
569 -- which means it guarantees that no elements can be added or removed from
570 -- the stream, it can merely transform them.
571 , map
572 , sequence
573 , mapM
575 -- ** Special Maps
576 , mapM_
577 , trace
578 , tap
579 , delay
581 -- ** Scanning
582 --
583 -- | A scan is more powerful than map. While a 'map' is a stateless loop, a
584 -- @scan@ is a stateful loop which means that a state can be shared across
585 -- all the loop iterations, therefore, future iterations can be impacted by
586 -- the state changes made by the past iterations. A scan yields the state
587 -- of the loop after each iteration. Like a map, a @postscan@ or @prescan@
588 -- does not add or remove elements in the stream, it just transforms them.
589 -- However, a @scan@ adds one extra element to the stream.
590 --
591 -- A left associative scan, also known as a prefix sum, can be thought of
592 -- as a stream transformation consisting of left folds of all prefixes of a
593 -- stream. Another way of thinking about it is that it streams all the
594 -- intermediate values of the accumulator while applying a left fold on the
595 -- input stream. A right associative scan, on the other hand, can be
596 -- thought of as a stream consisting of right folds of all the suffixes of
597 -- a stream.
598 --
599 -- The following equations hold for lists:
600 --
601 -- > scanl f z xs == map (foldl f z) $ inits xs
602 -- > scanr f z xs == map (foldr f z) $ tails xs
603 --
604 -- @
605 -- > scanl (+) 0 [1,2,3,4]
606 -- 0 = 0
607 -- 0 + 1 = 1
608 -- 0 + 1 + 2 = 3
609 -- 0 + 1 + 2 + 3 = 6
610 -- 0 + 1 + 2 + 3 + 4 = 10
611 --
612 -- > scanr (+) 0 [1,2,3,4]
613 -- 1 + 2 + 3 + 4 + 0 = 10
614 -- 2 + 3 + 4 + 0 = 9
615 -- 3 + 4 + 0 = 7
616 -- 4 + 0 = 4
617 -- 0 = 0
618 -- @
619 --
620 -- Left and right scans are duals:
621 --
622 -- > scanr f z xs == reverse $ scanl (flip f) z (reverse xs)
623 -- > scanl f z xs == reverse $ scanr (flip f) z (reverse xs)
624 --
625 -- A scan is a stateful map i.e. a combination of map and fold:
626 --
627 -- > map f xs = tail $ scanl (\_ x -> f x) z xs
628 -- > map f xs = reverse $ head $ scanr (\_ x -> f x) z xs
629 --
630 -- > foldl f z xs = last $ scanl f z xs
631 -- > foldr f z xs = head $ scanr f z xs
633 -- ** Left scans
634 , scanl'
635 , scanlM'
636 , postscanl'
637 , postscanlM'
638 , scanl1'
639 , scanl1M'
641 -- ** Scan Using Fold
642 , scan
643 , postscan
645 -- ** Filtering
646 -- | Remove some elements from the stream based on a predicate. In
647 -- imperative terms a filter over a stream corresponds to a loop with a
648 -- @continue@ clause for the cases when the predicate fails.
650 , filter
651 , filterM
653 -- ** Mapping Filters
654 -- | Mapping along with filtering
656 , mapMaybe
657 , mapMaybeM
659 -- ** Deleting Elements
660 -- | Deleting elements is a special case of de-interleaving streams.
661 , deleteBy
662 , uniq
664 -- ** Inserting Elements
665 -- | Inserting elements is a special case of interleaving/merging streams.
667 , insertBy
668 , intersperseM
669 , intersperse
671 -- ** Indexing
672 -- | Indexing can be considered as a special type of zipping where we zip a
673 -- stream with an index stream.
674 , indexed
675 , indexedR
677 -- ** Reordering Elements
678 , reverse
680 -- ** Trimming
681 -- | Take or remove elements from one or both ends of a stream.
682 , take
683 , takeWhile
684 , takeWhileM
685 , drop
686 , dropWhile
687 , dropWhileM
689 -- -- ** Breaking
691 , chunksOf
692 , intervalsOf
694 -- ** Searching
695 -- | Finding the presence or location of an element, a sequence of elements
696 -- or another stream within a stream.
698 -- -- ** Searching Elements
699 , findIndices
700 , elemIndices
702 -- ** Splitting
703 -- | In general we can express splitting in terms of parser combinators.
704 -- These are some common use functions for convenience and efficiency.
705 -- While parsers can fail these functions are designed to transform a
706 -- stream without failure with a predefined behavior for all cases.
707 --
708 -- In general, there are three possible ways of combining stream segments
709 -- with a separator. The separator could be prefixed to each segment,
710 -- suffixed to each segment, or it could be infixed between segments.
711 -- 'intersperse' and 'intercalate' operations are examples of infixed
712 -- combining whereas 'unlines' is an example of suffixed combining. When we
713 -- split a stream with separators we can split in three different ways,
714 -- each being an opposite of the three ways of combining.
715 --
716 -- Splitting may keep the separator or drop it. Depending on how we split,
717 -- the separator may be kept attached to the stream segments in prefix or
718 -- suffix position or as a separate element in infix position. Combinators
719 -- like 'splitOn' that use @On@ in their names drop the separator and
720 -- combinators that use 'With' in their names keep the separator. When a
721 -- segment is missing it is considered as empty, therefore, we never
722 -- encounter an error in parsing.
724 -- -- ** Splitting By Elements
725 , splitOn
726 , splitOnSuffix
728 , splitWithSuffix
729 , wordsBy -- strip, compact and split
731 -- ** Grouping
732 -- | Splitting a stream by combining multiple contiguous elements into
733 -- groups using some criterion.
734 , groups
735 , groupsBy
736 , groupsByRolling
738 -- * Combining Streams
739 -- | New streams can be constructed by appending, merging or zipping
740 -- existing streams.
742 -- ** Appending
743 -- | Streams form a 'Semigroup' and a 'Monoid' under the append
744 -- operation. Appending can be considered as a generalization of the `cons`
745 -- operation to consing a stream to a stream.
746 --
747 -- @
748 --
749 -- -------Stream m a------|-------Stream m a------|=>----Stream m a---
750 --
751 -- @
752 --
753 -- @
754 -- >> S.toList $ S.fromList [1,2] \<> S.fromList [3,4]
755 -- [1,2,3,4]
756 -- >> S.toList $ fold $ [S.fromList [1,2], S.fromList [3,4]]
757 -- [1,2,3,4]
758 -- @
759 , serial
761 -- ** Interleaving
762 , wSerial
764 -- ** Concurrent Scheduling
765 -- | Any exceptions generated by concurrent evaluation are propagated to
766 -- the consumer of the stream as soon as they occur. Exceptions from a
767 -- particular stream are guaranteed to arrive in the same order in the
768 -- output stream as they were generated in the input stream.
769 --
770 -- See 'maxThreads' and 'maxBuffer' to control the concurrency of these
771 -- combinators.
772 , ahead
773 , async
774 , wAsync
775 , parallel
776 , mkAsync
778 -- ** Merging
779 -- | Streams form a commutative semigroup under the merge
780 -- operation. Merging can be considered as a generalization of inserting an
781 -- element in a stream to interleaving a stream with another stream.
782 --
783 -- @
784 --
785 -- -------Stream m a------|
786 -- |=>----Stream m a---
787 -- -------Stream m a------|
788 -- @
789 --
791 -- , merge
792 , mergeBy
793 , mergeByM
794 , mergeAsyncBy
795 , mergeAsyncByM
797 -- ** Zipping
798 -- |
799 -- @
800 --
801 -- -------Stream m a------|
802 -- |=>----Stream m c---
803 -- -------Stream m b------|
804 -- @
805 --
806 , zipWith
807 , zipWithM
808 , zipAsyncWith
809 , zipAsyncWithM
811 -- ** Folding Streams of Streams
812 -- | Stream operations like map and filter represent loop processing in
813 -- imperative programming terms. Similarly, the imperative concept of
814 -- nested loops are represented by streams of streams. The 'concatMap'
815 -- operation represents nested looping.
816 -- A 'concatMap' operation loops over the input stream and then for each
817 -- element of the input stream generates another stream and then loops over
818 -- that inner stream as well producing effects and generating a single
819 -- output stream.
820 -- The 'Monad' instances of different stream types provide a more
821 -- convenient way of writing nested loops. Note that the monad bind
822 -- operation is just @flip concatMap@.
823 --
824 -- One dimension loops are just a special case of nested loops. For
825 -- example, 'concatMap' can degenerate to a simple map operation:
826 --
827 -- > map f m = S.concatMap (\x -> S.yield (f x)) m
828 --
829 -- Similarly, 'concatMap' can perform filtering by mapping an element to a
830 -- 'nil' stream:
831 --
832 -- > filter p m = S.concatMap (\x -> if p x then S.yield x else S.nil) m
833 --
835 , concatMapWith
836 , concatMap
837 , concatMapM
838 , unfoldMany
840 -- ** Folding Containers of Streams
841 -- | These are variants of standard 'Foldable' fold functions that use a
842 -- polymorphic stream sum operation (e.g. 'async' or 'wSerial') to fold a
843 -- finite container of streams. Note that these are just special cases of
844 -- the more general 'concatMapWith' operation.
845 --
846 , concatFoldableWith
847 , concatMapFoldableWith
848 , concatForFoldableWith
850 -- * Exceptions
851 -- | Most of these combinators inhibit stream fusion, therefore, when
852 -- possible, they should be called in an outer loop to mitigate the cost.
853 -- For example, instead of calling them on a stream of chars call them on a
854 -- stream of arrays before flattening it to a stream of chars.
855 --
856 , before
857 , after
858 , bracket
859 , onException
860 , finally
861 , handle
863 -- * Concurrency Control
864 -- $concurrency
865 , maxThreads
866 , maxBuffer
868 -- * Rate Limiting
869 , Rate (..)
870 , rate
871 , avgRate
872 , minRate
873 , maxRate
874 , constRate
876 -- * Stream Types
877 -- | Stream types that end with a @T@ (e.g. 'SerialT') are monad
878 -- transformers.
880 -- ** Serial Streams
881 -- $serial
882 , SerialT
883 , WSerialT
885 -- ** Speculative Streams
886 -- $ahead
887 , AheadT
889 -- ** Asynchronous Streams
890 -- $async
891 , AsyncT
892 , WAsyncT
893 , ParallelT
895 -- ** Zipping Streams
896 -- $zipping
897 , ZipSerialM
898 , ZipAsyncM
900 -- * IO Streams
901 , Serial
902 , WSerial
903 , Ahead
904 , Async
905 , WAsync
906 , Parallel
907 , ZipSerial
908 , ZipAsync
910 -- * Type Synonyms
911 , MonadAsync
913 -- * Stream Type Adapters
914 -- $adapters
915 , IsStream ()
917 , serially
918 , wSerially
919 , asyncly
920 , aheadly
921 , wAsyncly
922 , parallely
923 , zipSerially
924 , zipAsyncly
925 , adapt
927 -- * Deprecated
928 , once
929 , each
930 , scanx
931 , foldx
932 , foldxM
933 , foldr1
934 , runStream
935 , runN
936 , runWhile
937 , fromHandle
938 , toHandle
939 , concatUnfold
940 )
941where
943import Prelude
944 hiding (filter, drop, dropWhile, take, takeWhile, zipWith, foldr,
945 foldl, map, mapM, mapM_, sequence, all, any, sum, product, elem,
946 notElem, maximum, minimum, head, last, tail, length, null,
947 reverse, iterate, init, and, or, lookup, foldr1, (!!),
948 scanl, scanl1, repeat, replicate, concatMap, span)
950import Streamly.Internal.Data.Stream.IsStream
952-- $serial
953--
954-- Serial streams are /spatially ordered/, they execute the actions in the
955-- stream strictly one after the other.
956--
957-- There are two serial stream types 'SerialT' and 'WSerialT'. They differ
958-- only in the 'Semigroup' and 'Monad' instance behavior.
960-- $ahead
961--
962-- Speculative streams evaluate some future actions speculatively and
963-- concurrently, and keep the results ready for consumption. As in serial
964-- streams, results are consumed in the same order as the actions in the
965-- stream.
966--
967-- Even though the results of actions are ordered, the side effects are only
968-- partially ordered. Therefore, the semigroup operation is not commutative
969-- from the pure outputs perspective but commutative from side effects
970-- perspective.
972-- $async
973--
974-- Asynchronous streams evaluate some future actions concurrently, the results
975-- are given to the consumer as soon as they become available, they may not be
976-- in the same order as the actions in the stream.
977--
978-- The results of the actions as well as their side effects are partially
979-- ordered. Since the order of elements does not matter the 'Semigroup'
980-- operation is effectively commutative.
981--
982-- There are two asynchronous stream types 'AsyncT' and 'WAsyncT'. They differ
983-- only in the 'Semigroup' and 'Monad' instance behavior.
985-- $zipping
986--
987-- 'ZipSerialM' and 'ZipAsyncM', provide 'Applicative' instances for zipping the
988-- corresponding elements of two streams together. Note that these types are
989-- not monads.
991-- $rightfolds
992--
993-- Let's take a closer look at the @foldr@ definition for lists, as given3
994-- earlier:
995--
996-- @
997-- foldr f z (x:xs) = x \`f` foldr f z xs
998-- @
999--
1000-- @foldr@ invokes the fold step function @f@ as @f x (foldr f z xs)@. At each
1001-- invocation of @f@, @foldr@ gives us the next element in the input container
1002-- @x@ and a recursive expression @foldr f z xs@ representing the yet unbuilt
1003-- (lazy thunk) part of the output.
1005-- When @f x xs@ is lazy in @xs@ it can consume the input one element at a time
1006-- in FIFO order to build a lazy output expression. For example,
1008-- > f x remaining = show x : remaining
1010-- @take 2 $ foldr f [] (1:2:undefined)@ would consume the input lazily on
1011-- demand, consuming only first two elements and resulting in ["1", "2"]. @f@
1012-- can terminate recursion by not evaluating the @remaining@ part:
1014-- > f 2 remaining = show 2 : []
1015-- > f x remaining = show x : remaining
1017-- @f@ would terminate recursion whenever it sees element @2@ in the input.
1018-- Therefore, @take 2 $ foldr f [] (1:2:undefined)@ would work without any
1019-- problem.
1021-- On the other hand, if @f a b@ is strict in @b@ it would end up consuming the
1022-- whole input right away and expanding the recursive expression @b@ (i.e.
1023-- @foldr f z xs@) fully before it yields an output expression, resulting in
1024-- the following /right associated expression/:
1026-- @
1027-- foldr f z xs == x1 \`f` (x2 \`f` ...(xn \`f` z))
1028-- @
1030-- For example,
1032-- > f x remaining = x + remaining
1034-- With this definition, @foldr f 0 [1..1000]@, would recurse completely until
1035-- it reaches the terminating case @... `f` (1000 `f` 0)@, and then
1036-- start reducing the whole expression from right to left, therefore, consuming
1037-- the input elements in LIFO order. Thus, such an evaluation would require
1038-- memory proportional to the size of input. Try out @foldr (+) 0 (map (\\x ->
1039-- trace (show x) x) [1..10])@.
1041-- Notice the order of the arguments to the step function @f a b@. It follows
1042-- the order of @a@ and @b@ in the right associative recursive expression
1043-- generated by expanding @a \`f` b@.
1045-- A right fold is a pull fold, the step function is the puller, it can pull
1046-- more data from the input container by using its second argument in the
1047-- output expression or terminate pulling by not using it. As a corollary:
1049-- 1. a step function which is lazy in its second argument (usually functions
1050-- or constructors that build a lazy structure e.g. @(:)@) can pull lazily on
1051-- demand.
1052-- 2. a step function strict in its second argument (usually reducers e.g.
1053-- (+)) would end up pulling all of its input and buffer it in memory before
1054-- potentially reducing it.
1056-- A right fold is suitable for lazy reconstructions e.g. transformation,
1057-- mapping, filtering of /right associated input structures/ (e.g. cons lists).
1058-- Whereas a left fold is suitable for reductions (e.g. summing a stream of
1059-- numbers) of right associated structures. Note that these roles will reverse
1060-- for left associated structures (e.g. snoc lists). Most of our observations
1061-- here assume right associated structures, lists being the canonical example.
1063-- 1. A lazy FIFO style pull using a right fold allows pulling a potentially
1064-- /infinite/ input stream lazily, perform transformations on it, and
1065-- reconstruct a new structure without having to buffer the whole structure. In
1066-- contrast, a left fold would buffer the entire structure before the
1067-- reconstructed structure can be consumed.
1068-- 2. Even if buffering the entire input structure is ok, we need to keep in
1069-- mind that a right fold reconstructs structures in a FIFO style, whereas a
1070-- left fold reconstructs in a LIFO style, thereby reversing the order of
1071-- elements..
1072-- 3. A right fold has termination control and therefore can terminate early
1073-- without going through the entire input, a left fold cannot terminate
1074-- without consuming all of its input. For example, a right fold
1075-- implementation of 'or' can terminate as soon as it finds the first 'True'
1076-- element, whereas a left fold would necessarily go through the entire input
1077-- irrespective of that.
1078-- 4. Reduction (e.g. using (+) on a stream of numbers) using a right fold
1079-- occurs in a LIFO style, which means that the entire input gets buffered
1080-- before reduction starts. Whereas with a strict left fold reductions occur
1081-- incrementally in FIFO style. Therefore, a strict left fold is more suitable
1082-- for reductions.
1085-- $leftfolds
1087-- Note that the observations below about the behavior of a left fold assume
1088-- that we are working on a right associated structure like cons lists and
1089-- streamly streams. If we are working on a left associated structure (e.g.
1090-- snoc lists) the roles of right and left folds would reverse.
1092-- Let's take a closer look at the @foldl@ definition for lists given above:
1094-- @
1095-- foldl f z (x:xs) = foldl f (z \`f` x) xs
1096-- @
1098-- @foldl@ calls itself recursively, in each call it invokes @f@ as @f z x@
1099-- providing it with the result accumulated till now @z@ (the state) and the
1100-- next element from the input container. First call to @f@ is supplied with
1101-- the initial value of the accumulator @z@ and each subsequent call uses the
1102-- output of the previous call to @f z x@.
1104-- >> foldl' (+) 0 [1,2,3]
1105-- > 6
1107-- The recursive call at the head of the output expression is bound to be
1108-- evaluated until recursion terminates, therefore, a left fold always
1109-- /consumes the whole input container/. The following would result in an
1110-- error, even though the fold is not using the values at all:
1112-- >> foldl' (\_ _ -> 0) 0 (1:undefined)
1113-- > *** Exception: Prelude.undefined
1115-- As @foldl@ recurses, it builds the left associated expression shown below.
1116-- Notice, the order of the arguments to the step function @f b a@. It follows
1117-- the left associative recursive expression generated by expanding @b \`f` a@.
1119-- @
1120-- foldl f z xs == (((z \`f` x1) \`f` x2) ...) \`f` xn
1121-- @
1124-- The strict left fold @foldl'@ forces the reduction of its argument @z \`f`
1125-- x@ before using it, therefore it never builds the whole expression in
1126-- memory. Thus, @z \`f` x1@ would get reduced to @z1@ and then @z1 \`f` x2@
1127-- would get reduced to @z2@ and so on, incrementally reducing the expression
1128-- from left to right as it recurses, consuming the input in FIFO order. Try
1129-- out @foldl' (+) 0 (map (\\x -> trace (show x) x) [1..10])@ to see how it
1130-- works. For example:
1132-- @
1133-- > S.foldl' (+) 0 $ S.fromList [1,2,3,4]
1134-- 10
1135-- @
1137-- @
1138-- 0 + 1 = 1
1139-- 1 + 2 = 3
1140-- 3 + 3 = 6
1141-- 6 + 4 = 10
1142-- @
1144-- However, @foldl'@ evaluates the accumulator only to WHNF. It may further
1145-- help if the step function uses a strict data structure as accumulator to
1146-- improve performance and to keep the expression fully reduced at all times
1147-- during the fold.
1149-- A left fold can also build a new structure instead of reducing one if a
1150-- constructor is used as a fold step. However, it may not be very useful
1151-- because it will consume the whole input and construct the new structure in
1152-- memory before we can consume it. Thus the whole structure gets buffered in
1153-- memory. When the list constructor is used it would build a new list in
1154-- reverse (LIFO) order:
1156-- @
1157-- > S.foldl' (flip (:)) [] $ S.fromList [1,2,3,4]
1158-- [4,3,2,1]
1159-- @
1161-- A left fold is a push fold. The producer pushes its contents to the step
1162-- function of the fold. The step function therefore has no control to stop the
1163-- input, it can only discard it if it does not need it. We can also consider a
1164-- left fold as a state machine where the state is store in the accumulator,
1165-- the state can be modified based on new inputs that are pushed to the fold.
1167-- In general, a strict left fold is a reducing fold, whereas a right fold is a
1168-- constructing fold. A strict left fold reduces in a FIFO order whereas it
1169-- constructs in a LIFO order, and vice-versa for the right fold. See the
1170-- documentation of 'foldrM' for a discussion on where a left or right fold is
1171-- suitable.
1173-- To perform a left fold lazily without having to consume all the input one
1174-- can use @scanl@ to stream the intermediate results of the fold and consume
1175-- the resulting stream lazily.
1178-- $runningfolds
1180-- See "Streamly.Data.Fold" for an overview of composable folds. All folds in
1181-- this module can be expressed in terms of composable folds using 'fold'.
1183-- $application
1185-- Stream processing functions can be composed in a chain using function
1186-- application with or without the '$' operator, or with reverse function
1187-- application operator '&'. Streamly provides concurrent versions of these
1188-- operators applying stream processing functions such that each stage of the
1189-- stream can run in parallel. The operators start with a @|@; we can read '|$'
1190-- as "@parallel dollar@" to remember that @|@ comes before '$'.
1192-- $concurrency
1194-- These combinators can be used at any point in a stream composition to set
1195-- parameters to control the concurrency of the /argument stream/. A control
1196-- parameter set at any point remains effective for any concurrent combinators
1197-- used in the argument stream until it is reset by using the combinator again.
1198-- These control parameters have no effect on non-concurrent combinators in the
1199-- stream, or on non-concurrent streams.
1201-- /Pitfall:/ Remember that 'maxBuffer' in the following example applies to
1202-- 'mapM' and any other combinators that may follow it, and it does not apply
1203-- to the combinators before it:
1205-- @
1206-- ...
1207-- $ S.maxBuffer 10
1208-- $ S.mapM ...
1209-- ...
1210-- @
1212-- If we use '&' instead of '$' the situation will reverse, in the following
1213-- example, 'maxBuffer' does not apply to 'mapM', it applies to combinators
1214-- that come before it, because those are the arguments to 'maxBuffer':
1216-- @
1217-- ...
1218-- & S.maxBuffer 10
1219-- & S.mapM ...
1220-- ...
1221-- @
1223-- $adapters
1225-- You may want to use different stream composition styles at different points
1226-- in your program. Stream types can be freely converted or adapted from one
1227-- type to another. The 'IsStream' type class facilitates type conversion of
1228-- one stream type to another. It is not used directly, instead the type
1229-- combinators provided below are used for conversions.
1231-- To adapt from one monomorphic type (e.g. 'AsyncT') to another monomorphic
1232-- type (e.g. 'SerialT') use the 'adapt' combinator. To give a polymorphic code
1233-- a specific interpretation or to adapt a specific type to a polymorphic type
1234-- use the type specific combinators e.g. 'asyncly' or 'wSerially'. You
1235-- cannot adapt polymorphic code to polymorphic code, as the compiler would not know
1236-- which specific type you are converting from or to. If you see a an
1237-- @ambiguous type variable@ error then most likely you are using 'adapt'
1238-- unnecessarily on polymorphic code.