on 30c98dc help sign in
456 lines 15 kB history raw
1{-# OPTIONS_GHC -Wno-orphans #-}
3#include "inline.hs"
5-- |
6-- Module : Streamly.Data.Stream
7-- Copyright : (c) 2017 Composewell Technologies
8--
9-- License : BSD3
10-- Maintainer : streamly@composewell.com
11-- Stability : released
12-- Portability : GHC
13--
14-- To run examples in this module:
15--
16-- >>> import qualified Streamly.Data.Fold as Fold
17-- >>> import qualified Streamly.Data.Stream 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:
22--
23-- >>> effect n = print n >> return n
24--
25-- = Overview
26--
27-- Streamly is a framework for modular data flow based programming and
28-- declarative concurrency. Powerful stream fusion framework in streamly
29-- allows high performance combinatorial programming even when using byte level
30-- streams. Streamly API is similar to Haskell lists.
31--
32-- Streams can be constructed
33-- like lists, except that they use 'nil' instead of '[]' and 'cons' instead of
34-- ':'.
35--
36-- `cons` constructs a pure stream which is more or less the same as a list:
37--
38-- >>> import Streamly.Data.Stream (Stream, cons, consM, nil)
39-- >>> stream = 1 `cons` 2 `cons` nil :: Stream IO Int
40-- >>> Stream.fold Fold.toList stream -- IO [Int]
41-- [1,2]
42--
43-- 'consM' constructs a stream from effectful actions:
44--
45-- >>> stream = effect 1 `consM` effect 2 `consM` nil
46-- >>> Stream.fold Fold.toList stream
47-- 1
48-- 2
49-- [1,2]
50--
51-- == Console Echo Example
52--
53-- In the following example, 'repeatM' generates an infinite stream of 'String'
54-- by repeatedly performing the 'getLine' IO action. 'mapM' then applies
55-- 'putStrLn' on each element in the stream converting it to stream of '()'.
56-- Finally, 'drain' folds the stream to IO discarding the () values, thus
57-- producing only effects.
58--
59-- >>> import Data.Function ((&))
60--
61-- >>> :{
62-- echo =
63-- Stream.repeat getLine -- Stream IO (IO String)
64-- & Stream.sequence -- Stream IO String
65-- & Stream.mapM putStrLn -- Stream IO ()
66-- & Stream.fold Fold.drain -- IO ()
67-- :}
68--
69-- This is a console echo program. It is an example of a declarative loop
70-- written using streaming combinators. Compare it with an imperative @while@
71-- loop.
72--
73-- Hopefully, this gives you an idea how we can program declaratively by
74-- representing loops using streams. In this module, you can find all
75-- "Data.List" like functions and many more powerful combinators to perform
76-- common programming tasks.
77--
78-- Also see "Streamly.Internal.Data.Stream" module for many more @Pre-release@
79-- combinators. See the <https://github.com/composewell/streamly-examples>
80-- repository for many more real world examples of stream programming.
81--
82module Streamly.Data.Stream
83 (
84 Stream
85 -- * Construction
86 -- | Functions ending in the general shape @b -> Stream m a@.
87 --
88 -- See also: "Streamly.Internal.Data.Stream.Generate" for
89 -- @Pre-release@ functions.
91 -- ** Primitives
92 -- | Primitives to construct a stream from pure values or monadic actions.
93 -- All other stream construction and generation combinators described later
94 -- can be expressed in terms of these primitives. However, the special
95 -- versions provided in this module can be much more efficient in most
96 -- cases. Users can create custom combinators using these primitives.
97 , nil
98 , cons
99 , consM
100 -- , cons2 -- fused version
101 -- , consM2 -- fused version
103 -- ** Unfolding
104 -- | 'unfoldrM' is the most general way of generating a stream efficiently.
105 -- All other generation operations can be expressed using it.
106 , unfoldr
107 , unfoldrM
109 -- ** From Values
110 -- | Generate a monadic stream from a seed value or values.
111 , fromPure
112 , fromEffect
113 , repeat
114 , replicate
116 -- Note: Using enumeration functions e.g. 'Prelude.enumFromThen' turns out
117 -- to be slightly faster than the idioms like @[from, then..]@.
118 --
119 -- ** Enumeration
120 -- | We can use the 'Enum' type class to enumerate a type producing a list
121 -- and then convert it to a stream:
122 --
123 -- @
124 -- 'fromList' $ 'Prelude.enumFromThen' from then
125 -- @
126 --
127 -- However, this is not particularly efficient.
128 -- The 'Enumerable' type class provides corresponding functions that
129 -- generate a stream instead of a list, efficiently.
131 , Enumerable (..)
132 , enumerate
133 , enumerateTo
135 -- ** Iteration
136 , iterate
137 , iterateM
139 -- ** From Containers
140 -- | Convert an input structure, container or source into a stream. All of
141 -- these can be expressed in terms of primitives.
142 , fromList
143 , fromFoldable
145 -- ** From Unfolds
146 -- | Most of the above stream generation operations can also be expressed
147 -- using the corresponding unfolds in the "Streamly.Data.Unfold" module.
148 , unfold -- XXX rename to fromUnfold?
150 -- * Elimination
151 -- | Functions ending in the general shape @Stream m a -> m b@ or @Stream m
152 -- a -> m (b, Stream m a)@
153 --
154 -- See also: "Streamly.Internal.Data.Stream.Eliminate" for @Pre-release@
155 -- functions.
157-- EXPLANATION: In imperative terms a fold can be considered as a loop over the stream
158-- that reduces the stream to a single value.
159-- Left and right folds both use a fold function @f@ and an identity element
160-- @z@ (@zero@) to deconstruct a recursive data structure and reconstruct a
161-- new data structure. The new structure may be a recursive construction (a
162-- container) or a non-recursive single value reduction of the original
163-- structure.
164--
165-- Both right and left folds are mathematical duals of each other, they are
166-- functionally equivalent. Operationally, a left fold on a left associated
167-- structure behaves exactly in the same way as a right fold on a right
168-- associated structure. Similarly, a left fold on a right associated structure
169-- behaves in the same way as a right fold on a left associated structure.
170-- However, the behavior of a right fold on a right associated structure is
171-- operationally different (even though functionally equivalent) than a left
172-- fold on the same structure.
173--
174-- On right associated structures like Haskell @cons@ lists or Streamly
175-- streams, a lazy right fold is naturally suitable for lazy recursive
176-- reconstruction of a new structure, while a strict left fold is naturally
177-- suitable for efficient reduction. In right folds control is in the hand of
178-- the @puller@ whereas in left folds the control is in the hand of the
179-- @pusher@.
180--
181-- The behavior of right and left folds are described in detail in the
182-- individual fold's documentation. To illustrate the two folds for right
183-- associated @cons@ lists:
184--
185-- > foldr :: (a -> b -> b) -> b -> [a] -> b
186-- > foldr f z [] = z
187-- > foldr f z (x:xs) = x `f` foldr f z xs
188-- >
189-- > foldl :: (b -> a -> b) -> b -> [a] -> b
190-- > foldl f z [] = z
191-- > foldl f z (x:xs) = foldl f (z `f` x) xs
192--
193-- @foldr@ is conceptually equivalent to:
194--
195-- > foldr f z [] = z
196-- > foldr f z [x] = f x z
197-- > foldr f z xs = foldr f (foldr f z (tail xs)) [head xs]
198--
199-- @foldl@ is conceptually equivalent to:
200--
201-- > foldl f z [] = z
202-- > foldl f z [x] = f z x
203-- > foldl f z xs = foldl f (foldl f z (init xs)) [last xs]
204--
205-- Left and right folds are duals of each other.
206--
207-- @
208-- foldr f z xs = foldl (flip f) z (reverse xs)
209-- foldl f z xs = foldr (flip f) z (reverse xs)
210-- @
211--
212-- More generally:
213--
214-- @
215-- foldr f z xs = foldl g id xs z where g k x = k . f x
216-- foldl f z xs = foldr g id xs z where g x k = k . flip f x
217-- @
218--
220-- NOTE: Folds are inherently serial as each step needs to use the result of
221-- the previous step. However, it is possible to fold parts of the stream in
222-- parallel and then combine the results using a monoid.
224 -- ** Primitives
225 -- Consuming a part of the stream and returning the rest. Functions
226 -- ending in the general shape @Stream m a -> m (b, Stream m a)@
227 , uncons
229 -- ** Folding
230 -- XXX Need to have a general parse operation here which can be used to
231 -- express all others.
232 , fold -- XXX rename to run? We can have a Stream.run and Fold.run.
233 -- XXX fold1 can be achieved using Monoids or Refolds.
234 , foldBreak
235 , foldContinue
237 -- ** Parsing
238 , parse
239 , parseBreak
241 -- -- ** Lazy Right Folds
242 -- Consuming a stream to build a right associated expression, suitable
243 -- for lazy evaluation. Evaluation of the input happens when the output of
244 -- the fold is evaluated, the fold output is a lazy thunk.
245 --
246 -- This is suitable for stream transformation operations, for example,
247 -- operations like mapping a function over the stream.
248 -- , foldrM
249 -- , foldr
251 -- * Mapping
252 -- | Stateless one-to-one transformations. Use 'fmap' for mapping a pure
253 -- function on a stream.
255 -- EXPLANATION:
256 -- In imperative terms a map operation can be considered as a loop over
257 -- the stream that transforms the stream into another stream by performing
258 -- an operation on each element of the stream.
259 --
260 -- 'map' is the least powerful transformation operation with strictest
261 -- guarantees. A map, (1) is a stateless loop which means that no state is
262 -- allowed to be carried from one iteration to another, therefore,
263 -- operations on different elements are guaranteed to not affect each
264 -- other, (2) is a strictly one-to-one transformation of stream elements
265 -- which means it guarantees that no elements can be added or removed from
266 -- the stream, it can merely transform them.
267 , sequence
268 , mapM
269 -- , trace -- XXX Use "tracing" map instead?
270 , tap
271 , delay
273 -- * Scanning
274 -- | Stateful one-to-one transformations.
275 --
276 -- See also: "Streamly.Internal.Data.Stream.Transform" for
277 -- @Pre-release@ functions.
278 , scan
279 , postscan
280 -- XXX postscan1 can be implemented using Monoids or Refolds.
281 -- Indexing can be considered as a special type of zipping where we zip a
282 -- stream with an index stream.
283 , indexed
284 , indexedR
286 -- * Insertion
287 -- | Add elements to the stream.
289 -- Inserting elements is a special case of interleaving/merging streams.
290 , insertBy
291 , intersperseM
292 , intersperse
294 -- * Filtering
295 -- | Remove elements from the stream.
297 -- ** Stateless Filters
298 -- | 'mapMaybeM' is the most general stateless filtering operation. All
299 -- other filtering operations can be expressed using it.
300 -- EXPLANATION:
301 -- In imperative terms a filter over a stream corresponds to a loop with a
302 -- @continue@ clause for the cases when the predicate fails.
304 , mapMaybe
305 , mapMaybeM
306 , filter
307 , filterM
309 -- ** Stateful Filters
310 -- | 'scanMaybe' is the most general stateful filtering operation. The
311 -- filtering folds (folds returning a 'Maybe' type) in
312 -- "Streamly.Internal.Data.Fold" can be used along with 'scanMaybe' to
313 -- perform stateful filtering operations in general.
314 , scanMaybe
315 , take
316 , takeWhile
317 , takeWhileM
318 , drop
319 , dropWhile
320 , dropWhileM
321 , deleteBy
322 , uniq
324 -- ** Searching
325 -- Finding the presence or location of an element, a sequence of elements
326 -- or another stream within a stream.
328 -- -- ** Searching Elements
329 , findIndices
330 , elemIndices
332 -- * Combining Two Streams
333 -- ** Appending
334 , append
335 , append2
337 -- ** Interleaving
338 , interleave
339 -- , interleave2
341 -- ** Merging
342 -- | Merging of @n@ streams can be performed by combining the streams pair
343 -- wise using
344 -- 'Streamly.Internal.Data.Stream.IsStream.Expand.concatPairsWith' to give
345 -- O(n * log n) time complexity.
346 -- If used with 'concatMapWith' it will have O(n^2) performance.
348 , mergeBy
349 , mergeByM
350 -- , mergeBy2
351 -- , mergeByM2
353 -- ** Zipping
354 -- | Zipping of @n@ streams can be performed by combining the streams pair
355 -- wise using
356 -- 'Streamly.Internal.Data.Stream.IsStream.Expand.concatPairsWith' with
357 -- O(n * log n) time complexity.
358 -- If used with 'concatMapWith' it will have O(n^2) performance.
359 , zipWith
360 , zipWithM
361 -- , zipWith2
362 -- , zipWithM2
364 -- * Unfold Each
365 , unfoldMany
366 , intercalate
367 , intercalateSuffix
369 -- * Stream of streams
370 -- | Stream operations like map and filter represent loop processing in
371 -- imperative programming terms. Similarly, the imperative concept of
372 -- nested loops are represented by streams of streams. The 'concatMap'
373 -- operation represents nested looping.
374 -- A 'concatMap' operation loops over the input stream and then for each
375 -- element of the input stream generates another stream and then loops over
376 -- that inner stream as well producing effects and generating a single
377 -- output stream.
378 -- The 'Monad' instances of different stream types provide a more
379 -- convenient way of writing nested loops. Note that the monad bind
380 -- operation is just @flip concatMap@.
381 --
382 -- One dimension loops are just a special case of nested loops. For
383 -- example, 'concatMap' can degenerate to a simple map operation:
384 --
385 -- > map f m = S.concatMap (\x -> S.fromPure (f x)) m
386 --
387 -- Similarly, 'concatMap' can perform filtering by mapping an element to a
388 -- 'nil' stream:
389 --
390 -- > filter p m = S.concatMap (\x -> if p x then S.fromPure x else S.nil) m
391 --
393 , concatMapWith
394 , concatMap
395 , concatMapM
397 -- * Repeated Fold
398 , foldMany -- XXX Rename to foldRepeat
400 -- * Buffered Operations
401 -- | Operations that require buffering of the stream.
402 -- Reverse is essentially a left fold followed by an unfold.
403 , reverse
405 -- * Multi-Stream folds
406 -- | Operations that consume multiple streams at the same time.
407 , eqBy
408 , cmpBy
409 , isPrefixOf
410 , isSubsequenceOf
412 -- trimming sequences
413 , stripPrefix
415 -- * Exceptions
416 -- | Most of these combinators inhibit stream fusion, therefore, when
417 -- possible, they should be called in an outer loop to mitigate the cost.
418 -- For example, instead of calling them on a stream of chars call them on a
419 -- stream of arrays before flattening it to a stream of chars.
420 --
421 -- See also: "Streamly.Internal.Data.Stream.Exception" for
422 -- @Pre-release@ functions.
424 , onException
425 , handle
427 -- * Resource Management
428 -- | 'bracket' is the most general resource management operation, all other
429 -- operations can be expressed using it.
430 , before
431 , after
432 , finally
433 , bracket
435 -- * Lifting Inner Monad
436 -- | See also: "Streamly.Internal.Data.Stream.Lift" for
437 -- @Pre-release@ functions.
439 , liftInner
440 , runReaderT
441 , runStateT
443 -- -- * Stream Types
444 -- $serial
445 -- , Interleave
446 -- , Zip
447 )
448where
450import Streamly.Internal.Data.Stream
451import Prelude
452 hiding (filter, drop, dropWhile, take, takeWhile, zipWith, foldr,
453 foldl, map, mapM, mapM_, sequence, all, any, sum, product, elem,
454 notElem, maximum, minimum, head, last, tail, length, null,
455 reverse, iterate, init, and, or, lookup, foldr1, (!!),
456 scanl, scanl1, repeat, replicate, concatMap, span)