1{-# OPTIONS_GHC -Wno-orphans #-}
6-- Module : Streamly.Prelude
7-- Copyright : (c) 2017 Composewell Technologies
10-- Maintainer : streamly@composewell.com
11-- Stability : experimental
14-- To run examples in this module:
16-- >>> import qualified Streamly.Data.Fold as Fold
17-- >>> import qualified Streamly.Prelude as Stream
19-- We will add some more imports in the examples as needed.
21-- For effectful streams we will use the following IO action that blocks for
24-- >>> import Control.Concurrent (threadDelay)
27-- threadDelay (n * 1000000) -- sleep for n seconds
28-- putStrLn (show n ++ " sec") -- print "n sec"
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.
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
48-- `cons` constructs a pure stream which is more or less the same as a list:
50-- >>> import Streamly.Prelude (SerialT, cons, consM, nil)
51-- >>> stream = 1 `cons` 2 `cons` nil :: SerialT IO Int
52-- >>> Stream.toList stream -- IO [Int]
55-- 'consM' constructs a stream from effectful actions:
57-- >>> stream = delay 1 `consM` delay 2 `consM` nil
58-- >>> Stream.toList stream
63-- == Console Echo Program
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.
71-- >>> import Data.Function ((&))
75-- Stream.repeatM getLine -- SerialT IO String
76-- & Stream.mapM putStrLn -- SerialT IO ()
77-- & Stream.drain -- IO ()
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@
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.
93-- == Polymorphic Combinators
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,
100-- repeatM :: (IsStream t, MonadAsync m) => m a -> t m a
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).
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
112-- drain :: Monad m => SerialT m a -> m ()
115-- We can force a certain stream type in polymorphic code by using "Stream Type
116-- Adaptors". For example, to force 'AsyncT':
118-- >>> Stream.drain $ Stream.asyncly $ Stream.replicateM 10 $ delay 1
121-- == Combining two streams
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.
130-- For example, the `parallel` combinator schedules both the streams
133-- >>> stream1 = Stream.fromListM [delay 3, delay 4]
134-- >>> stream2 = Stream.fromListM [delay 1, delay 2]
135-- >>> Stream.toList $ stream1 `parallel` stream2
138-- We can chain the operations to combine more than two streams:
140-- >>> stream3 = Stream.fromListM [delay 1, delay 2]
141-- >>> Stream.toList $ stream1 `parallel` stream2 `parallel` stream3
144-- Concurrent generation ('consM') and concurrent merging of streams is the
145-- fundamental basis of all concurrency in streamly.
147-- == Combining many streams
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:
155-- import qualified Streamly.Network.Inet.TCP as TCP
156-- import qualified Streamly.Network.Socket as Socket
158-- Stream.unfold TCP.acceptOnPort 8090
159-- & Stream.concatMapWith Stream.parallel (Stream.unfold Socket.read)
162-- See the @streamly-examples@ repository for a full working example.
164-- == Concurrent Nested Loops
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.
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.
181-- 'SerialT' executes actions serially, so the total delay in the following
182-- example is @2 + 1 = 3@ seconds:
184-- >>> stream = delay 2 `consM` delay 1 `consM` nil
185-- >>> Stream.toList stream -- IO [Int]
190-- 'AsyncT' executes the actions concurrently, so the total delay is @max 2 1 =
193-- >>> Stream.toList $ Stream.asyncly stream -- IO [Int]
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.
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:
205-- >>> Stream.toList $ Stream.aheadly stream -- IO [Int]
210-- == Semigroup Instance
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.
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).
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:
224-- >>> stream1 = Stream.fromListM [delay 1, delay 2]
225-- >>> stream2 = Stream.fromListM [delay 3, delay 4]
226-- >>> Stream.toList $ stream1 <> stream2
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
237-- >>> Stream.toList $ Stream.wSerially $ stream1 <> stream2
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.
248-- == Concurrent Combinators
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'.
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:
257-- >>> Stream.drain $ Stream.replicateM 10 $ delay 1
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:
264-- >>> Stream.drain $ Stream.asyncly $ Stream.replicateM 10 $ delay 1
267-- We can use 'mapM' to map an action concurrently:
269-- >>> f x = delay 1 >> return (x + 1)
270-- >>> Stream.toList $ Stream.aheadly $ Stream.mapM f $ Stream.fromList [1..3]
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.
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.
282-- == Automatic Concurrency Control
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.
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
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:
305-- Stream.asyncly $ ... concurrent combinator here ... $ Stream.serially $ ...
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
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
323 -- | Functions ending in the general shape @b -> t m a@
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.
340 -- | Generalized way of generating a stream efficiently.
346 -- | Generate a monadic stream from a seed value or values.
354 -- Note: Using enumeration functions e.g. 'Prelude.enumFromThen' turns out
355 -- to be slightly faster than the idioms like @[from, then..]@.
358 -- | We can use the 'Enum' type class to enumerate a type producing a list
359 -- and then convert it to a stream:
362 -- 'fromList' $ 'Prelude.enumFromThen' from then
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.
377 -- ** From Generators
378 -- | Generate a monadic stream from a seed value and a generator function.
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.
391 -- | Functions ending in the general shape @t m a -> m b@
393 -- ** Running a 'Fold'
400 -- | Functions ending in the general shape @t m a -> m (b, t m a)@
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
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.
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
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:
435-- > foldr :: (a -> b -> b) -> b -> [a] -> b
437-- > foldr f z (x:xs) = x `f` foldr f z xs
439-- > foldl :: (b -> a -> b) -> b -> [a] -> b
441-- > foldl f z (x:xs) = foldl f (z `f` x) xs
443-- @foldr@ is conceptually equivalent to:
446-- > foldr f z [x] = f x z
447-- > foldr f z xs = foldr f (foldr f z (tail xs)) [head xs]
449-- @foldl@ is conceptually equivalent to:
452-- > foldl f z [x] = f z x
453-- > foldl f z xs = foldl f (foldl f z (init xs)) [last xs]
455-- Left and right folds are duals of each other.
458-- foldr f z xs = foldl (flip f) z (reverse xs)
459-- foldl f z xs = foldr (flip f) z (reverse xs)
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
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.
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.
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.
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)
516 -- -- | Folds that extract selected elements of a stream or their properties.
525 -- -- ** To Boolean (Partial Folds)
526 -- -- | Folds that summarize the stream to a boolean value.
536 -- | Convert a stream into a container holding all the values.
539 -- ** Folding Concurrently
543 -- ** Multi-Stream folds
549 -- trimming sequences
552 -- * Parallel Function Application
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.
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.
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.
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
599 -- The following equations hold for lists:
601 -- > scanl f z xs == map (foldl f z) $ inits xs
602 -- > scanr f z xs == map (foldr f z) $ tails xs
605 -- > scanl (+) 0 [1,2,3,4]
610 -- 0 + 1 + 2 + 3 + 4 = 10
612 -- > scanr (+) 0 [1,2,3,4]
613 -- 1 + 2 + 3 + 4 + 0 = 10
620 -- Left and right scans are duals:
622 -- > scanr f z xs == reverse $ scanl (flip f) z (reverse xs)
623 -- > scanl f z xs == reverse $ scanr (flip f) z (reverse xs)
625 -- A scan is a stateful map i.e. a combination of map and fold:
627 -- > map f xs = tail $ scanl (\_ x -> f x) z xs
628 -- > map f xs = reverse $ head $ scanr (\_ x -> f x) z xs
630 -- > foldl f z xs = last $ scanl f z xs
631 -- > foldr f z xs = head $ scanr f z xs
641 -- ** Scan Using Fold
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.
653 -- ** Mapping Filters
654 -- | Mapping along with filtering
659 -- ** Deleting Elements
660 -- | Deleting elements is a special case of de-interleaving streams.
664 -- ** Inserting Elements
665 -- | Inserting elements is a special case of interleaving/merging streams.
672 -- | Indexing can be considered as a special type of zipping where we zip a
673 -- stream with an index stream.
677 -- ** Reordering Elements
681 -- | Take or remove elements from one or both ends of a stream.
695 -- | Finding the presence or location of an element, a sequence of elements
696 -- or another stream within a stream.
698 -- -- ** Searching Elements
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.
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.
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
729 , wordsBy -- strip, compact and split
732 -- | Splitting a stream by combining multiple contiguous elements into
733 -- groups using some criterion.
738 -- * Combining Streams
739 -- | New streams can be constructed by appending, merging or zipping
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.
749 -- -------Stream m a------|-------Stream m a------|=>----Stream m a---
754 -- >> S.toList $ S.fromList [1,2] \<> S.fromList [3,4]
756 -- >> S.toList $ fold $ [S.fromList [1,2], S.fromList [3,4]]
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.
770 -- See 'maxThreads' and 'maxBuffer' to control the concurrency of these
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.
785 -- -------Stream m a------|
786 -- |=>----Stream m a---
787 -- -------Stream m a------|
801 -- -------Stream m a------|
802 -- |=>----Stream m c---
803 -- -------Stream m b------|
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
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@.
824 -- One dimension loops are just a special case of nested loops. For
825 -- example, 'concatMap' can degenerate to a simple map operation:
827 -- > map f m = S.concatMap (\x -> S.yield (f x)) m
829 -- Similarly, 'concatMap' can perform filtering by mapping an element to a
832 -- > filter p m = S.concatMap (\x -> if p x then S.yield x else S.nil) m
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.
847 , concatMapFoldableWith
848 , concatForFoldableWith
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.
863 -- * Concurrency Control
877 -- | Stream types that end with a @T@ (e.g. 'SerialT') are monad
885 -- ** Speculative Streams
889 -- ** Asynchronous Streams
895 -- ** Zipping Streams
913 -- * Stream Type Adapters
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
954-- Serial streams are /spatially ordered/, they execute the actions in the
955-- stream strictly one after the other.
957-- There are two serial stream types 'SerialT' and 'WSerialT'. They differ
958-- only in the 'Semigroup' and 'Monad' instance behavior.
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
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
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.
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.
982-- There are two asynchronous stream types 'AsyncT' and 'WAsyncT'. They differ
983-- only in the 'Semigroup' and 'Monad' instance behavior.
987-- 'ZipSerialM' and 'ZipAsyncM', provide 'Applicative' instances for zipping the
988-- corresponding elements of two streams together. Note that these types are
993-- Let's take a closer look at the @foldr@ definition for lists, as given3
997-- foldr f z (x:xs) = x \`f` foldr f z xs
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
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/:
1027-- foldr f z xs == x1 \`f` (x2 \`f` ...(xn \`f` z))
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
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
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
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:
1095-- foldl f z (x:xs) = foldl f (z \`f` x) xs
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]
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@.
1120-- foldl f z xs == (((z \`f` x1) \`f` x2) ...) \`f` xn
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:
1133-- > S.foldl' (+) 0 $ S.fromList [1,2,3,4]
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
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:
1157-- > S.foldl' (flip (:)) [] $ S.fromList [1,2,3,4]
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
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.
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'.
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 '$'.
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:
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':
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.
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list