on a05abfc help sign in
streamly/docs/Tutorial.hs
542 lines 18 kB history raw
1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
2-- |
3-- Module : Tutorial
4-- Copyright : (c) 2017 Composewell Technologies
5--
6-- License : BSD3
7-- Maintainer : streamly@composewell.com
8--
9-- In this tutorial we will show how Streamly can be used for idiomatic
10-- dataflow programming. Before you go through this tutorial we recommend that
11-- you take a look at the Streamly Getting Started guide so that you are ready
12-- to try out the examples.
14module Tutorial
15 (
16 -- * Stream Types
17 -- $streams
19 -- * Imports and Supporting Code
20 -- $imports
22 -- * Generating Streams
23 -- $generating
25 -- * Eliminating Streams
26 -- $eliminating
28 -- * Transforming Streams
29 -- $transformation
31 -- * Merging Streams
33 -- ** Semigroup Style
34 -- $semigroup
36 -- *** Deep Serial Composition ('Serial')
37 -- $serial
39 -- *** Wide Serial Composition ('WSerial')
40 -- $interleaved
42 -- ** Monoid Style
43 -- $monoid
45 -- * Nesting Streams
46 -- $nesting
48 -- ** Monad
49 -- $monad
51 -- *** Deep Serial Nesting ('Serial')
52 -- $regularSerial
54 -- *** Wide Serial Nesting ('WSerial')
55 -- $interleavedNesting
57 -- *** Exercise
58 -- $monadExercise
60 -- ** Applicative
61 -- $applicative
63 -- ** Functor
64 -- $functor
66 -- * Zipping Streams
67 -- $zipping
69 -- ** Serial Zipping
70 -- $serialzip
72 -- * Where to go next?
73 -- $furtherReading
74 )
75where
77import Streamly.Prelude
78import Data.Semigroup
79import Control.Applicative
80import Control.Monad
81import Control.Monad.IO.Class (MonadIO(..))
82import Control.Monad.Trans.Class (MonadTrans (lift))
84-- CAUTION: please keep setup and imports sections in sync
86-- $setup
87-- >>> :m
88-- >>> import Data.Function ((&))
89-- >>> import Streamly.Prelude ((|:), (|&))
90-- >>> import qualified Streamly.Prelude as Stream
91-- >>> import qualified Streamly.Data.Fold as Fold
92--
94-- $imports
95--
96-- In most of example snippets we do not repeat the imports. Where imports are
97-- not explicitly specified use the imports shown below.
98--
99-- >>> :m
100-- >>> import Data.Function ((&))
101-- >>> import Streamly.Prelude ((|:), (|&))
102-- >>> import qualified Streamly.Prelude as Stream
103-- >>> import qualified Streamly.Data.Fold as Fold
104--
106-- $streams
107--
108-- The monadic stream API offered by Streamly is very close to the Haskell
109-- "Prelude" pure lists' API, it can be considered as a natural extension of
110-- lists to monadic actions. Streamly streams provide concurrent composition
111-- and merging of streams. It can be considered as a concurrent list
112-- transformer.
113--
114-- The 'Serial' type is almost a drop in replacement for pure lists,
115-- pure lists are a special case of monadic streams. If you use 'nil' in place
116-- of '[]' and '|:' in place ':' you can replace a list with a 'Serial' stream.
117-- The only difference is that the elements must be monadic type and to operate
118-- on the streams we must use the corresponding functions from
119-- "Streamly.Prelude" instead of using the base "Prelude".
121-- $generating
122--
123-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
124-- a monadic action at the head of the stream.
125--
126-- >>> Stream.toList Stream.nil
127-- []
128--
129-- Stream.toList $ getLine |: getLine |: Stream.nil
130-- hello
131-- world
132-- ["hello","world"]
133--
134-- To create a singleton stream from a pure value use 'fromPure' or 'pure' and to
135-- create a singleton stream from a monadic action use 'fromEffect'. Note that in
136-- case of Zip applicative streams "pure" repeats the value to generate an
137-- infinite stream.
138--
139-- >>> Stream.toList $ pure 1
140-- [1]
141--
142-- >>> Stream.toList $ Stream.fromPure 1
143-- [1]
144--
145-- Stream.toList $ Stream.fromEffect getLine
146-- hello
147-- ["hello"]
148--
149-- To create a stream from pure values in a 'Foldable' container use
150-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
151--
152-- >>> Stream.toList $ Stream.fromFoldable [1..3]
153-- [1,2,3]
154--
155-- >>> Stream.toList $ Prelude.foldr Stream.cons Stream.nil [1..3]
156-- [1,2,3]
157--
158-- To create a stream from monadic actions in a 'Foldable' container just use a
159-- right fold using 'consM' and 'nil':
160--
161-- >>> Stream.drain $ Prelude.foldr (|:) Stream.nil [putStr "Hello ", putStrLn "world!"]
162-- Hello world!
163--
164-- For more ways to construct a stream see the module "Streamly.Prelude".
166-- $eliminating
167--
168-- We have already seen 'drain' and toList to eliminate a stream in the
169-- examples above. 'drain' runs a stream discarding the results i.e. only
170-- for effects. 'toList' runs the stream and collects the results in a list.
171--
172-- For other ways to eliminate a stream see the @Folding@ section in
173-- "Streamly.Prelude" module.
175-- $transformation
176--
177-- Transformation over a stream is the equivalent of a @for@ loop construct in
178-- imperative paradigm. We iterate over every element in the stream and perform
179-- certain transformations for each element. Transformations may involve
180-- mapping functions over the elements, filtering elements from the stream or
181-- folding all the elements in the stream into a single value. Streamly streams
182-- are exactly like lists and you can perform all the transformations in the
183-- same way as you would on lists.
184--
185-- Here is a simple console echo program that just echoes every input line,
186-- forever:
187--
188-- >>> :{
189-- echo =
190-- Stream.repeatM getLine
191-- & Stream.mapM putStrLn
192-- & Stream.drain
193-- :}
194--
195-- The following code snippet reads lines from standard input, filters blank
196-- lines, drops the first non-blank line, takes the next two, up cases them,
197-- numbers them and prints them:
198--
199-- >>> import Data.Char (toUpper)
200-- >>> :{
201-- main =
202-- Stream.repeatM getLine
203-- & Stream.filter (not . null)
204-- & Stream.drop 1
205-- & Stream.take 2
206-- & fmap (map toUpper)
207-- & Stream.zipWith (\n s -> show n ++ " " ++ s) (Stream.fromFoldable [1..])
208-- & Stream.mapM putStrLn
209-- & Stream.drain
210-- :}
211--
213-- $semigroup
214--
215-- We can combine two streams into a single stream using semigroup composition
216-- operation '<>'. Streams can be combined in many different ways as described
217-- in the following sections, the '<>' operation behaves differently depending
218-- on the stream type in effect. The stream type and therefore the composition
219-- style can be changed at any point using one of the type combinators as
220-- discussed earlier.
222-- $serial
223--
224-- The 'Semigroup' operation '<>' of the 'Serial' type combines the two streams
225-- in a /serial depth first/ manner. We use the 'fromSerial' type combinator to
226-- effect 'Serial' style of composition. We can also use an explicit 'Serial'
227-- type annotation for the stream to achieve the same effect. However, since
228-- 'Serial' is the default type unless explicitly specified by using a
229-- combinator, we can omit using an explicit combinator or type annotation for
230-- this style of composition.
231--
232-- When two streams with multiple elements are combined in this manner, the
233-- monadic actions in the two streams are performed sequentially i.e. first all
234-- actions in the first stream are performed sequentially and then all actions
235-- in the second stream are performed sequentially. We call it
236-- /serial depth first/ as the full depth of one stream is fully traversed
237-- before we move to the next. The following example prints the sequence 1, 2,
238-- 3, 4:
239--
240-- >>> stream1 = print 1 |: print 2 |: Stream.nil
241-- >>> stream2 = print 3 |: print 4 |: Stream.nil
242-- >>> Stream.drain $ stream1 <> stream2
243-- 1
244-- 2
245-- 3
246-- 4
247--
248-- All actions in both the streams are performed serially in the same thread.
249--
250-- The polymorphic version of the binary operation '<>' of the 'Serial' type is
251-- 'serial'. We can use 'serial' to join streams in a sequential manner
252-- irrespective of the type of stream:
253--
254-- >>> Stream.drain $ stream1 `Stream.serial` stream2
255-- 1
256-- 2
257-- 3
258-- 4
259--
261-- $interleaved
262--
263-- The 'Semigroup' operation '<>' of the 'WSerial' type combines the two
264-- streams in a /serial breadth first/ manner. We use the fromWSerial type
265-- combinator to effect 'WSerial' style of composition. We can also use the
266-- 'WSerial' type annotation for the stream to achieve the same effect.
267--
268-- When two streams with multiple elements are combined in this manner, we
269-- traverse all the streams in a breadth first manner i.e. one action from each
270-- stream is performed and yielded to the resulting stream before we come back
271-- to the first stream again and so on.
272-- The following example prints the sequence 1, 3, 2, 4
273--
274-- >>> stream1 = print 1 |: print 2 |: Stream.nil
275-- >>> stream2 = print 3 |: print 4 |: Stream.nil
276-- >>> Stream.drain $ Stream.fromWSerial $ stream1 <> stream2
277-- 1
278-- 3
279-- 2
280-- 4
281--
282-- Even though the monadic actions of the two streams are performed in an
283-- interleaved manner they are all performed serially in the same thread.
284--
285-- The polymorphic version of the 'WSerial' binary operation '<>' is called
286-- 'wSerial'. We can use 'wSerial' to join streams in an interleaved manner
287-- irrespective of the type, notice that we have not used the fromWSerial
288-- combinator in the following example:
289--
290-- >>> Stream.drain $ stream1 `Stream.wSerial` stream2
291-- 1
292-- 3
293-- 2
294-- 4
295--
296-- Note that this composition cannot be used to fold infinite number of streams
297-- since it requires preserving the state until a stream is finished.
299-- $monoid
300--
301-- We can use 'Monoid' instances to fold a container of streams in the desired
302-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
303-- to fold streams using the polymorphic combine operations:
304--
305-- * 'concatFoldableWith' is like 'fold', it folds a 'Foldable' container of
306-- streams using the given composition operator.
307-- * 'concatMapFoldableWith' is like 'foldMap', it folds like
308-- @concatFoldableWith@ but also maps a function before folding.
309-- * 'concatForFoldableWith' is like @concatMapFoldableWith@ but the container
310-- argument comes before the function argument.
311--
312-- All of the following are equivalent:
313--
314-- >>> :{
315-- traced = Stream.fromEffect . print
316-- main = do
317-- Stream.drain $ foldMap traced [1..10]
318-- Stream.drain $ Stream.concatFoldableWith Stream.serial (map traced [1..10])
319-- Stream.drain $ Stream.concatMapFoldableWith Stream.serial traced [1..10]
320-- Stream.drain $ Stream.concatForFoldableWith Stream.serial [1..10] traced
321-- :}
322--
324-- $nesting
325--
326-- Till now we discussed ways to apply transformations on a stream or to merge
327-- streams together to create another stream. We mentioned earlier that
328-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
329-- We will now discuss the concept of a nested composition of streams which is
330-- analogous to nested @for@ loops in the imperative paradigm. Functional
331-- programmers call this style of composition a list transformer or @ListT@.
332-- Logic programmers call it a logic monad or non-deterministic composition,
333-- but for ordinary imperative minded people like me it is easier to think in
334-- terms of good old nested @for@ loops.
335--
336-- $monad
337--
338-- In functional programmer's parlance the 'Monad' instances of different
339-- 'IsStream' types implement non-determinism, exploring all possible
340-- combination of choices from both the streams. From an imperative
341-- programmer's point of view it behaves like nested loops i.e. for each
342-- element in the first stream and for each element in the second stream
343-- execute the body of the loop.
344--
345-- The 'Monad' instances of 'Serial', 'WSerial', 'Async' and 'WAsync'
346-- stream types support different flavors of nested looping. In other words,
347-- they are all variants of list transformer. The nesting behavior of these
348-- types correspond exactly to the way they merge streams as we discussed in
349-- the previous section.
350--
352-- $regularSerial
353--
354-- The 'Monad' composition of the 'Serial' type behaves like a standard list
355-- transformer. This is the default when we do not use an explicit type
356-- combinator. However, the 'fromSerial' type combinator can be used to switch to
357-- this style of composition. We will see how this style of composition works
358-- in the following examples.
359--
360-- Let's start with an example with a simple @for@ loop without any nesting.
361-- For simplicity of illustration we are using streams of pure values in all
362-- the examples. However, the streams could also be made of monadic actions
363-- instead.
364--
365-- >>> :{
366-- Stream.drain $ do
367-- x <- Stream.fromFoldable [3,2,1]
368-- Stream.fromEffect $ print x
369-- :}
370-- 3
371-- 2
372-- 1
373--
374-- As we can see, the code after the @fromFoldable@ statement is run three
375-- times, once for each value of @x@ drawn from the stream. All the three
376-- iterations are serial and run in the same thread one after another. In
377-- imperative terms this is equivalent to a @for@ loop with three iterations.
378--
379-- We can write the console echo program that we wrote earlier using the monad
380-- instance:
381--
382-- >>> :{
383-- main =
384-- Stream.drain $ do
385-- x <- Stream.repeatM getLine
386-- Stream.fromEffect $ putStrLn x
387-- :}
388--
389-- When multiple streams are composed using this style they nest in a DFS
390-- manner:
391--
392-- >>> :{
393-- Stream.drain $ do
394-- x <- Stream.fromFoldable [1,2]
395-- y <- Stream.fromFoldable [3,4]
396-- Stream.fromEffect $ print (x, y)
397-- :}
398-- (1,3)
399-- (1,4)
400-- (2,3)
401-- (2,4)
402--
403-- i.e. inner loop iterations ((1,3), (1,4)) are executed before we proceed to
404-- the next iteration of the outer loop ((2,3), (2,4)). This behaves just like
405-- nested @for@ loops in imperative programming.
406--
407-- Notice that this is analogous to merging streams of type 'Serial' or merging
408-- streams using 'serial'.
410-- $interleavedNesting
411--
412-- The 'Monad' composition of 'WSerial' type interleaves the iterations of
413-- outer and inner loops in a nested loop composition.
414--
415-- >>> :{
416-- Stream.drain $ Stream.fromWSerial $ do
417-- x <- Stream.fromFoldable [1,2]
418-- y <- Stream.fromFoldable [3,4]
419-- Stream.fromEffect $ print (x, y)
420-- :}
421-- (1,3)
422-- (2,3)
423-- (1,4)
424-- (2,4)
425--
426-- Note that (2,3) is preferred to (1,4). This works exactly the same way as
427-- the merging of two streams using 'wSerial' works.
428--
429-- The fromWSerial type combinator can be used to switch to this style of
430-- composition. Alternatively, a type annotation can be used to specify the
431-- type of the stream as 'WSerial'.
432--
434-- $monadExercise
435--
436-- Streamly code is usually written in a way that is agnostic of the
437-- specific monadic composition type. We use a polymorphic type with a
438-- 'IsStream' type class constraint. When running the stream we can choose the
439-- specific mode of composition. For example take a look at the following code.
440--
441-- >>> :{
442-- composed :: (Stream.IsStream t, Monad (t IO)) => t IO ()
443-- composed = do
444-- sz <- sizes
445-- cl <- colors
446-- sh <- shapes
447-- Stream.fromEffect $ print (sz, cl, sh)
448-- where
449-- sizes = Stream.fromFoldable [1, 2, 3]
450-- colors = Stream.fromFoldable ["red", "green", "blue"]
451-- shapes = Stream.fromFoldable ["triangle", "square", "circle"]
452-- :}
453--
454-- Now we can interpret this in whatever way we want:
455--
456-- @
457-- main = Stream.'drain' $ Stream.'fromSerial' $ composed
458-- main = Stream.'drain' $ Stream.'fromWSerial' $ composed
459-- main = Stream.'drain' $ Stream.'fromAsync' $ composed
460-- main = Stream.'drain' $ Stream.'fromWAsync' $ composed
461-- main = Stream.'drain' $ Stream.'fromParallel' $ composed
462-- @
463--
464-- As an exercise try to figure out the output of this code for each mode of
465-- composition.
467-- $functor
468--
469-- 'fmap' transforms a stream by mapping a function on all elements of the
470-- stream. 'fmap' behaves in the same way for all stream types, it is always
471-- serial.
472--
473-- >>> (Stream.toList $ fmap show $ Stream.fromFoldable [1..10]) >>= print
474-- ["1","2","3","4","5","6","7","8","9","10"]
475--
476-- Also see functions 'mapM' and 'sequence' from "Streamly.Prelude" module
477-- which can map actions concurrently depending on the type of the input stream.
479-- $applicative
480--
481-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
482-- zipping applicatives separate types 'ZipSerial' and 'ZipAsync' are
483-- provided.
484--
485-- The following is an example of 'Serial' applicative, it runs all iterations
486-- serially:
487--
488-- >>> p n = Stream.fromEffect (print n) >> return n
489-- >>> s1 = p 1 <> p 2
490-- >>> s2 = p 3 <> p 4
491--
492-- >>> (Stream.toList $ Stream.fromSerial $ (,) <$> s1 <*> s2) >>= print
493-- 1
494-- 3
495-- 4
496-- 2
497-- 3
498-- 4
499-- [(1,3),(1,4),(2,3),(2,4)]
500--
501-- Similarly, 'WSerial' applicative runs the iterations in an interleaved
502-- order but being serial it too takes a total of 17 seconds:
503--
504-- >>> (Stream.toList $ Stream.fromWSerial $ (,) <$> s1 <*> s2) >>= print
505-- 1
506-- 3
507-- 2
508-- 3
509-- 4
510-- 4
511-- [(1,3),(2,3),(1,4),(2,4)]
513-- $zipping
514--
515-- Zipping is a special transformation where the corresponding elements of two
516-- streams are combined together using a zip function producing a new stream of
517-- outputs. Two different types are provided for serial and concurrent zipping.
518-- These types provide an applicative instance that can be used to lift
519-- functions to zip the argument streams.
520-- Also see the zipping functions in the "Streamly.Prelude" module.
522-- $serialzip
523--
524-- The applicative instance of 'ZipSerial' type zips streams serially.
525-- 'fromZipSerial' type combinator can be used to switch to serial applicative
526-- zip composition:
527--
528-- >>> p n = Stream.fromEffect (print n) >> return n
529-- >>> s1 = Stream.fromSerial $ p 1 <> p 2
530-- >>> s2 = Stream.fromSerial $ p 3 <> p 4
531-- >>> (Stream.toList $ Stream.fromZipSerial $ (,) <$> s1 <*> s2) >>= print
532-- 1
533-- 3
534-- 2
535-- 4
536-- [(1,3),(2,4)]
537--
539-- $furtherReading
540--
541-- * Read the concurrent streams tutorial
542-- * See the examples in <https://github.com/composewell/streamly-examples streamly-examples> repo.