2{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE FlexibleContexts #-}
5#if __GLASGOW_HASKELL__ >= 800
6{-# OPTIONS_GHC -Wno-orphans #-}
12-- Module : Streamly.Prelude
13-- Copyright : (c) 2017 Harendra Kumar
16-- Maintainer : streamly@composewell.com
17-- Stability : experimental
20-- This module is designed to be imported qualified:
23-- import qualified Streamly.Prelude as S
26-- Functions with the suffix @M@ are general functions that work on monadic
27-- arguments. The corresponding functions without the suffix @M@ work on pure
28-- arguments and can in general be derived from their monadic versions but are
29-- provided for convenience and for consistency with other pure APIs in the
32-- In many cases, short definitions of the combinators are provided in the
33-- documentation for illustration. The actual implementation may differ for
34-- performance reasons.
36-- Functions having a 'MonadAsync' constraint work concurrently when used with
37-- appropriate stream type combinator. Please be careful to not use 'parallely'
38-- with infinite streams.
40-- Deconstruction and folds accept a 'SerialT' type instead of a polymorphic
41-- type to ensure that streams always have a concrete monomorphic type by
42-- default, reducing type errors. In case you want to use any other type of
43-- stream you can use one of the type combinators provided in the "Streamly"
44-- module to convert the stream type.
46module Streamly.Prelude
50 -- | Primitives to construct a stream from pure values or monadic actions.
51 -- All other stream construction and generation combinators described later
52 -- can be expressed in terms of these primitives. However, the special
53 -- versions provided in this module can be much more efficient in most
54 -- cases. Users can create custom combinators using these primitives.
64 -- | Generate a monadic stream from a seed value or values.
72 -- Note: Using enumeration functions e.g. 'Prelude.enumFromThen' turns out
73 -- to be slightly faster than the idioms like @[from, then..]@.
76 -- | We can use the 'Enum' type class to enumerate a type producing a list
77 -- and then convert it to a stream:
80 -- 'fromList' $ 'Prelude.enumFromThen' from then
83 -- However, this is not particularly efficient.
84 -- The 'Enumerable' type class provides corresponding functions that
85 -- generate a stream instead of a list, efficiently.
92 -- | Generate a monadic stream from a seed value and a generator function.
101 -- ** From Containers
102 -- | Convert an input structure, container or source into a stream. All of
103 -- these can be expressed in terms of primitives.
112 -- | It is easy to express all the folds in terms of the 'uncons' primitive,
113 -- however the specific implementations provided later are generally more
121-- | In imperative terms a fold can be considered as a loop over the stream
122-- that reduces the stream to a single value.
123-- Left and right folds use a fold function @f@ and an identity element @z@
124-- (@zero@) to recursively deconstruct a structure and then combine and reduce
125-- the values or transform and reconstruct a new container.
127-- In general, a right fold is suitable for transforming and reconstructing a
128-- right associated structure (e.g. cons lists and streamly streams) and a left
129-- fold is suitable for reducing a right associated structure. The behavior of
130-- right and left folds are described in detail in the individual fold's
131-- documentation. To illustrate the two folds for cons lists:
133-- > foldr :: (a -> b -> b) -> b -> [a] -> b
135-- > foldr f z (x:xs) = x `f` foldr f z xs
137-- > foldl :: (b -> a -> b) -> b -> [a] -> b
139-- > foldl f z (x:xs) = foldl f (z `f` x) xs
141-- @foldr@ is conceptually equivalent to:
144-- > foldr f z [x] = f x z
145-- > foldr f z xs = foldr f (foldr f z (tail xs)) [head xs]
147-- @foldl@ is conceptually equivalent to:
150-- > foldl f z [x] = f z x
151-- > foldl f z xs = foldl f (foldl f z (init xs)) [last xs]
153-- Left and right folds are duals of each other.
156-- foldr f z xs = foldl (flip f) z (reverse xs)
157-- foldl f z xs = foldr (flip f) z (reverse xs)
163-- foldr f z xs = foldl g id xs z where g k x = k . f x
164-- foldl f z xs = foldr g id xs z where g x k = k . flip f x
168-- As a general rule, foldr cannot have state and foldl cannot have control.
170-- NOTE: Folds are inherently serial as each step needs to use the result of
171-- the previous step. However, it is possible to fold parts of the stream in
172-- parallel and then combine the results using a monoid.
187 -- ** Composable Left Folds
193 -- | Folds that are guaranteed to evaluate the whole stream.
195 -- -- ** To Summary (Full Folds)
196 -- -- | Folds that summarize the stream to a single value.
204 -- -- ** To Summary (Maybe) (Full Folds)
205 -- -- | Folds that summarize a non-empty stream to a 'Just' value and return
206 -- 'Nothing' for an empty stream.
212 -- , toListRev -- experimental
216 -- | Folds that generate a lazy structure. Note that the generated
217 -- structure may not be lazy if the underlying monad is strict.
219 -- -- ** To Containers (Full Folds)
220 -- -- | Convert or divert a stream into an output structure, container or
225 -- | Folds that may terminate before evaluating the whole stream. These
226 -- folds strictly evaluate the stream until the result is determined.
228 -- -- ** To Elements (Partial Folds)
232 -- -- | Folds that extract selected elements of a stream or their properties.
241 -- -- ** To Boolean (Partial Folds)
242 -- -- | Folds that summarize the stream to a boolean value.
251 -- ** Multi-Stream folds
259 -- trimming sequences
269 -- | In imperative terms a map operation can be considered as a loop over
270 -- the stream that transforms the stream into another stream by performing
271 -- an operation on each element of the stream.
273 -- 'map' is the least powerful transformation operation with strictest
274 -- guarantees. A map, (1) is a stateless loop which means that no state is
275 -- allowed to be carried from one iteration to another, therefore,
276 -- operations on different elements are guaranteed to not affect each
277 -- other, (2) is a strictly one-to-one transformation of stream elements
278 -- which means it guarantees that no elements can be added or removed from
279 -- the stream, it can merely transform them.
291 -- | A scan is more powerful than map. While a 'map' is a stateless loop, a
292 -- @scan@ is a stateful loop which means that a state can be shared across
293 -- all the loop iterations, therefore, future iterations can be impacted by
294 -- the state changes made by the past iterations. A scan yields the state
295 -- of the loop after each iteration. Like a map, a @postscan@ or @prescan@
296 -- does not add or remove elements in the stream, it just transforms them.
297 -- However, a @scan@ adds one extra element to the stream.
299 -- A left associative scan, also known as a prefix sum, can be thought of
300 -- as a stream transformation consisting of left folds of all prefixes of a
301 -- stream. Another way of thinking about it is that it streams all the
302 -- intermediate values of the accumulator while applying a left fold on the
303 -- input stream. A right associative scan, on the other hand, can be
304 -- thought of as a stream consisting of right folds of all the suffixes of
307 -- The following equations hold for lists:
309 -- > scanl f z xs == map (foldl f z) $ inits xs
310 -- > scanr f z xs == map (foldr f z) $ tails xs
313 -- > scanl (+) 0 [1,2,3,4]
318 -- 0 + 1 + 2 + 3 + 4 = 10
320 -- > scanr (+) 0 [1,2,3,4]
321 -- 1 + 2 + 3 + 4 + 0 = 10
328 -- Left and right scans are duals:
330 -- > scanr f z xs == reverse $ scanl (flip f) z (reverse xs)
331 -- > scanl f z xs == reverse $ scanr (flip f) z (reverse xs)
333 -- A scan is a stateful map i.e. a combination of map and fold:
335 -- > map f xs = tail $ scanl (\_ x -> f x) z xs
336 -- > map f xs = reverse $ head $ scanr (\_ x -> f x) z xs
338 -- > foldl f z xs = last $ scanl f z xs
339 -- > foldr f z xs = head $ scanr f z xs
351 -- ** Scan Using Fold
366 -- | Remove some elements from the stream based on a predicate. In
367 -- imperative terms a filter over a stream corresponds to a loop with a
368 -- @continue@ clause for the cases when the predicate fails.
373 -- ** Mapping Filters
374 -- | Mapping along with filtering
379 -- ** Deleting Elements
380 -- | Deleting elements is a special case of de-interleaving streams.
383 -- , uniqBy -- by predicate e.g. to remove duplicate "/" in a path
384 -- , uniqOn -- to remove duplicate sequences
385 -- , pruneBy -- dropAround + uniqBy - like words
387 -- ** Inserting Elements
388 -- | Inserting elements is a special case of interleaving/merging streams.
394 -- , intersperseBySpan
395 -- , intersperseByIndices -- using an index function/stream
396 -- , intersperseByTime
397 -- , intersperseByEvent
399 -- -- * Inserting Streams in Streams
404 -- | Indexing can be considered as a special type of zipping where we zip a
405 -- stream with an index stream.
409 -- , timestampedR -- timer
411 -- ** Reordering Elements
416 -- | Take or remove elements from one or both ends of a stream.
432 -- , splitAt -- spanN
433 -- , splitIn -- sessionN
436 -- , span -- spanWhile
437 -- , break -- breakBefore
445 -- breakOnSeq/breakOnArray -- on a fixed sequence
446 -- breakOnStream -- on a stream
449 -- | Streams can be sliced into segments in space or in time. We use the
450 -- term @chunk@ to refer to a spatial length of the stream (spatial window)
451 -- and the term @session@ to refer to a length in time (time window).
453 -- In imperative terms, grouped folding can be considered as a nested loop
454 -- where we loop over the stream to group elements and then loop over
455 -- individual groups to fold them to a single value that is yielded in the
464 -- | Finding the presence or location of an element, a sequence of elements
465 -- or another stream within a stream.
467 -- -- ** Searching Elements
471 -- -- *** Searching Sequences
472 -- , seqIndices -- search a sequence in the stream
474 -- -- *** Searching Multiple Sequences
475 -- , seqIndices -- search a sequence in the stream
477 -- -- ** Searching Streams
478 -- -- | Finding a stream within another stream.
481 -- | In general we can express splitting in terms of parser combinators.
482 -- These are some common use functions for convenience and efficiency.
483 -- While parsers can fail these functions are designed to transform a
484 -- stream without failure with a predefined behavior for all cases.
486 -- In general, there are three possible ways of combining stream segments
487 -- with a separator. The separator could be prefixed to each segment,
488 -- suffixed to each segment, or it could be infixed between segments.
489 -- 'intersperse' and 'intercalate' operations are examples of infixed
490 -- combining whereas 'unlines' is an example of suffixed combining. When we
491 -- split a stream with separators we can split in three different ways,
492 -- each being an opposite of the three ways of combining.
494 -- Splitting may keep the separator or drop it. Depending on how we split,
495 -- the separator may be kept attached to the stream segments in prefix or
496 -- suffix position or as a separate element in infix position. Combinators
497 -- like 'splitOn' that use @On@ in their names drop the separator and
498 -- combinators that use 'With' in their names keep the separator. When a
499 -- segment is missing it is considered as empty, therefore, we never
500 -- encounter an error in parsing.
502 -- -- ** Splitting By Elements
510 , wordsBy -- strip, compact and split
512 -- -- *** Splitting By Sequences
514 -- , splitOnSuffixSeq
515 -- , splitOnPrefixSeq
517 -- Keeping the delimiters
519 -- , splitBySeqSuffix
520 -- , splitBySeqPrefix
523 -- Splitting By Multiple Sequences
525 -- , splitOnAnySuffixSeq
526 -- , splitOnAnyPrefixSeq
528 -- -- ** Splitting By Streams
529 -- -- | Splitting a stream using another stream as separator.
532 -- | Splitting a stream by combining multiple contiguous elements into
533 -- groups using some criterion.
539 -- * Windowed Classification
540 -- | Split the stream into windows or chunks in space or time. Each window
541 -- can be associated with a key, all events associated with a particular
542 -- key in the window can be folded to a single result. The stream is split
543 -- into windows of specified size, the window can be terminated early if
544 -- the closing flag is specified in the input stream.
546 -- The term "chunk" is used for a space window and the term "session" is
547 -- used for a time window.
549 -- ** Tumbling Windows
550 -- | A new window starts after the previous window is finished.
551 -- , classifyChunksOf
552 -- , classifySessionsOf
554 -- ** Keep Alive Windows
555 -- | The window size is extended if an event arrives within the specified
556 -- window size. This can represent sessions with idle or inactive timeout.
557 -- , classifyKeepAliveChunks
558 -- , classifyKeepAliveSessions
561 -- ** Sliding Windows
562 -- | A new window starts after the specified slide from the previous
563 -- window. Therefore windows can overlap.
564 , classifySlidingChunks
565 , classifySlidingSessions
567 -- ** Sliding Window Buffers
568 -- , slidingChunkBuffer
569 -- , slidingSessionBuffer
572 -- * Combining Streams
573 -- | New streams can be constructed by appending, merging or zipping
577 -- | Streams form a 'Semigroup' and a 'Monoid' under the append
578 -- operation. Appending can be considered as a generalization of the `cons`
579 -- operation to consing a stream to a stream.
583 -- -------Stream m a------|-------Stream m a------|=>----Stream m a---
588 -- >> S.toList $ S.fromList [1,2] \<> S.fromList [3,4]
590 -- >> S.toList $ fold $ [S.fromList [1,2], S.fromList [3,4]]
595 -- | Streams form a commutative semigroup under the merge
596 -- operation. Merging can be considered as a generalization of inserting an
597 -- element in a stream to interleaving a stream with another stream.
601 -- -------Stream m a------|
602 -- |=>----Stream m a---
603 -- -------Stream m a------|
617 -- -------Stream m a------|
618 -- |=>----Stream m c---
619 -- -------Stream m b------|
628 -- ** Folding Containers of Streams
629 -- | These are variants of standard 'Foldable' fold functions that use a
630 -- polymorphic stream sum operation (e.g. 'async' or 'wSerial') to fold a
631 -- finite container of streams. Note that these are just special cases of
632 -- the more general 'concatMapWith' operation.
639 -- ** Folding Streams of Streams
640 -- | Stream operations like map and filter represent loop processing in
641 -- imperative programming terms. Similarly, the imperative concept of
642 -- nested loops are represented by streams of streams. The 'concatMap'
643 -- operation represents nested looping.
644 -- A 'concatMap' operation loops over the input stream and then for each
645 -- element of the input stream generates another stream and then loops over
646 -- that inner stream as well producing effects and generating a single
648 -- The 'Monad' instances of different stream types provide a more
649 -- convenient way of writing nested loops. Note that the monad bind
650 -- operation is just @flip concatMap@.
652 -- One dimension loops are just a special case of nested loops. For
653 -- example, 'concatMap' can degenerate to a simple map operation:
655 -- > map f m = S.concatMap (\x -> S.yield (f x)) m
657 -- Similarly, 'concatMap' can perform filtering by mapping an element to a
660 -- > filter p m = S.concatMap (\x -> if p x then S.yield x else S.nil) m
663 -- XXX add stateful concatMapWith
694 hiding (filter, drop, dropWhile, take, takeWhile, zipWith, foldr,
695 foldl, map, mapM, mapM_, sequence, all, any, sum, product, elem,
696 notElem, maximum, minimum, head, last, tail, length, null,
697 reverse, iterate, init, and, or, lookup, foldr1, (!!),
698 scanl, scanl1, repeat, replicate, concatMap, span)
700import Streamly.Internal.Prelude
704-- Let's take a closer look at the @foldr@ definition for lists, as given
708-- foldr f z (x:xs) = x \`f` foldr f z xs
711-- @foldr@ invokes the fold step function @f@ as @f x (foldr f z xs)@. At each
712-- invocation of @f@, @foldr@ gives us the next element in the input container
713-- @x@ and a recursive expression @foldr f z xs@ representing the yet unbuilt
714-- (lazy thunk) part of the output.
716-- When @f x xs@ is lazy in @xs@ it can consume the input one element at a time
717-- in FIFO order to build a lazy output expression. For example,
719-- > f x remaining = show x : remaining
721-- @take 2 $ foldr f [] (1:2:undefined)@ would consume the input lazily on
722-- demand, consuming only first two elements and resulting in ["1", "2"]. @f@
723-- can terminate recursion by not evaluating the @remaining@ part:
725-- > f 2 remaining = show 2 : []
726-- > f x remaining = show x : remaining
728-- @f@ would terminate recursion whenever it sees element @2@ in the input.
729-- Therefore, @take 2 $ foldr f [] (1:2:undefined)@ would work without any
732-- On the other hand, if @f a b@ is strict in @b@ it would end up consuming the
733-- whole input right away and expanding the recursive expression @b@ (i.e.
734-- @foldr f z xs@) fully before it yields an output expression, resulting in
735-- the following /right associated expression/:
738-- foldr f z xs == x1 \`f` (x2 \`f` ...(xn \`f` z))
743-- > f x remaining = x + remaining
745-- With this definition, @foldr f 0 [1..1000]@, would recurse completely until
746-- it reaches the terminating case @... `f` (1000 `f` 0)@, and then
747-- start reducing the whole expression from right to left, therefore, consuming
748-- the input elements in LIFO order. Thus, such an evaluation would require
749-- memory proportional to the size of input. Try out @foldr (+) 0 (map (\\x ->
750-- trace (show x) x) [1..10])@.
752-- Notice the order of the arguments to the step function @f a b@. It follows
753-- the order of @a@ and @b@ in the right associative recursive expression
754-- generated by expanding @a \`f` b@.
756-- A right fold is a pull fold, the step function is the puller, it can pull
757-- more data from the input container by using its second argument in the
758-- output expression or terminate pulling by not using it. As a corollary:
760-- 1. a step function which is lazy in its second argument (usually functions
761-- or constructors that build a lazy structure e.g. @(:)@) can pull lazily on
763-- 2. a step function strict in its second argument (usually reducers e.g.
764-- (+)) would end up pulling all of its input and buffer it in memory before
765-- potentially reducing it.
767-- A right fold is suitable for lazy reconstructions e.g. transformation,
768-- mapping, filtering of /right associated input structures/ (e.g. cons lists).
769-- Whereas a left fold is suitable for reductions (e.g. summing a stream of
770-- numbers) of right associated structures. Note that these roles will reverse
771-- for left associated structures (e.g. snoc lists). Most of our observations
772-- here assume right associated structures, lists being the canonical example.
774-- 1. A lazy FIFO style pull using a right fold allows pulling a potentially
775-- /infinite/ input stream lazily, perform transformations on it, and
776-- reconstruct a new structure without having to buffer the whole structure. In
777-- contrast, a left fold would buffer the entire structure before the
778-- reconstructed structure can be consumed.
779-- 2. Even if buffering the entire input structure is ok, we need to keep in
780-- mind that a right fold reconstructs structures in a FIFO style, whereas a
781-- left fold reconstructs in a LIFO style, thereby reversing the order of
783-- 3. A right fold has termination control and therefore can terminate early
784-- without going through the entire input, a left fold cannot terminate
785-- without consuming all of its input. For example, a right fold
786-- implementation of 'or' can terminate as soon as it finds the first 'True'
787-- element, whereas a left fold would necessarily go through the entire input
788-- irrespective of that.
789-- 4. Reduction (e.g. using (+) on a stream of numbers) using a right fold
790-- occurs in a LIFO style, which means that the entire input gets buffered
791-- before reduction starts. Whereas with a strict left fold reductions occur
792-- incrementally in FIFO style. Therefore, a strict left fold is more suitable
798-- Note that the observations below about the behavior of a left fold assume
799-- that we are working on a right associated structure like cons lists and
800-- streamly streams. If we are working on a left associated structure (e.g.
801-- snoc lists) the roles of right and left folds would reverse.
803-- Let's take a closer look at the @foldl@ definition for lists given above:
806-- foldl f z (x:xs) = foldl f (z \`f` x) xs
809-- @foldl@ calls itself recursively, in each call it invokes @f@ as @f z x@
810-- providing it with the result accumulated till now @z@ (the state) and the
811-- next element from the input container. First call to @f@ is supplied with
812-- the initial value of the accumulator @z@ and each subsequent call uses the
813-- output of the previous call to @f z x@.
815-- >> foldl' (+) 0 [1,2,3]
818-- The recursive call at the head of the output expression is bound to be
819-- evaluated until recursion terminates, therefore, a left fold always
820-- /consumes the whole input container/. The following would result in an
821-- error, even though the fold is not using the values at all:
823-- >> foldl' (\_ _ -> 0) 0 (1:undefined)
824-- > *** Exception: Prelude.undefined
826-- As @foldl@ recurses, it builds the left associated expression shown below.
827-- Notice, the order of the arguments to the step function @f b a@. It follows
828-- the left associative recursive expression generated by expanding @b \`f` a@.
831-- foldl f z xs == (((z \`f` x1) \`f` x2) ...) \`f` xn
835-- The strict left fold @foldl'@ forces the reduction of its argument @z \`f`
836-- x@ before using it, therefore it never builds the whole expression in
837-- memory. Thus, @z \`f` x1@ would get reduced to @z1@ and then @z1 \`f` x2@
838-- would get reduced to @z2@ and so on, incrementally reducing the expression
839-- from left to right as it recurses, consuming the input in FIFO order. Try
840-- out @foldl' (+) 0 (map (\\x -> trace (show x) x) [1..10])@ to see how it
841-- works. For example:
844-- > S.foldl' (+) 0 $ S.fromList [1,2,3,4]
855-- However, @foldl'@ evaluates the accumulator only to WHNF. It may further
856-- help if the step function uses a strict data structure as accumulator to
857-- improve performance and to keep the expression fully reduced at all times
860-- A left fold can also build a new structure instead of reducing one if a
861-- constructor is used as a fold step. However, it may not be very useful
862-- because it will consume the whole input and construct the new structure in
863-- memory before we can consume it. Thus the whole structure gets buffered in
864-- memory. When the list constructor is used it would build a new list in
865-- reverse (LIFO) order:
868-- > S.foldl' (flip (:)) [] $ S.fromList [1,2,3,4]
872-- A left fold is a push fold. The producer pushes its contents to the step
873-- function of the fold. The step function therefore has no control to stop the
874-- input, it can only discard it if it does not need it. We can also consider a
875-- left fold as a state machine where the state is store in the accumulator,
876-- the state can be modified based on new inputs that are pushed to the fold.
878-- In general, a strict left fold is a reducing fold, whereas a right fold is a
879-- constructing fold. A strict left fold reduces in a FIFO order whereas it
880-- constructs in a LIFO order, and vice-versa for the right fold. See the
881-- documentation of 'foldrM' for a discussion on where a left or right fold is
884-- To perform a left fold lazily without having to consume all the input one
885-- can use @scanl@ to stream the intermediate results of the fold and consume
886-- the resulting stream lazily.
891-- "Streamly.Data.Fold" module defines composable left folds which can be combined
892-- together in many interesting ways. Those folds can be run using 'fold'.
893-- The following two ways of folding are equivalent in functionality and
896-- >>> S.fold FL.sum (S.enumerateFromTo 1 100)
898-- >>> S.sum (S.enumerateFromTo 1 100)
901-- However, left folds cannot terminate early even if it does not need to
902-- consume more input to determine the result. Therefore, the performance is
903-- equivalent only for full folds like 'sum' and 'length'. For partial folds
904-- like 'head' or 'any' the the folds defined in this module may be much more
905-- efficient because they are implemented as right folds that terminate as soon
906-- as we get the result. Note that when a full fold is composed with a partial
907-- fold in parallel the performance is not impacted as we anyway have to
908-- consume the whole stream due to the full fold.
910-- >>> S.head (1 `S.cons` undefined)
912-- >>> S.fold FL.head (1 `S.cons` undefined)
913-- *** Exception: Prelude.undefined
915-- However, we can wrap the fold in a scan to convert it into a lazy stream of
916-- fold steps. We can then terminate the stream whenever we want. For example,
918-- >>> S.toList $ S.take 1 $ S.scan FL.head (1 `S.cons` undefined)
921-- The following example extracts the input stream up to a point where the
922-- running average of elements is no more than 10:
926-- $ S.map (fromJust . fst)
927-- $ S.takeWhile (\\(_,x) -> x <= 10)
928-- $ S.postscan ((,) \<$> FL.last \<*> avg) (S.enumerateFromTo 1.0 100.0)
931-- [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0]
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