1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
3-- Module : User.Tutorials.Tutorial
4-- Copyright : (c) 2017 Composewell Technologies
7-- Maintainer : streamly@composewell.com
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 User.Tutorials.Tutorial
22 -- * Imports and Supporting Code
25 -- * Generating Streams
28 -- * Eliminating Streams
31 -- * Transforming Streams
39 -- *** Deep Serial Composition ('Serial')
42 -- *** Wide Serial Composition ('WSerial')
54 -- *** Deep Serial Nesting ('Serial')
57 -- *** Wide Serial Nesting ('WSerial')
58 -- $interleavedNesting
75 -- * Where to go next?
80import Streamly.Data.Stream
82import Control.Applicative
84import Control.Monad.IO.Class (MonadIO(..))
85import Control.Monad.Trans.Class (MonadTrans (lift))
87-- CAUTION: please keep setup and imports sections in sync
89-- XXX This tutorial has to be re-written.
93-- In most of example snippets we do not repeat the imports. Where
94-- imports are not explicitly specified use the imports shown below.
97-- >>> :set -fno-warn-deprecations
98-- >>> import Data.Function ((&))
99-- >>> import Streamly.Prelude ((|:), (|&))
100-- >>> import Streamly.Data.Stream (Stream)
101-- >>> import Streamly.Internal.Data.Stream.Cross (CrossStream(..))
102-- >>> import qualified Streamly.Prelude as Stream
103-- >>> import qualified Streamly.Data.Fold as Fold
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
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".
123-- 'nil' represents an empty stream and 'consM' or its operator form '|:' adds
124-- a monadic action at the head of the stream.
126-- >>> Stream.toList Stream.nil
129-- Stream.toList $ getLine |: getLine |: Stream.nil
134-- To create a singleton stream from a pure value use 'fromPure' and to
135-- create a singleton stream from a monadic action use 'fromEffect'.
137-- >>> Stream.toList $ Stream.fromPure 1
140-- Stream.toList $ Stream.fromEffect getLine
144-- To create a stream from pure values in a 'Foldable' container use
145-- 'fromFoldable' which is equivalent to a fold using 'cons' and 'nil':
147-- >>> Stream.toList $ Stream.fromFoldable [1..3]
150-- >>> Stream.toList $ Prelude.foldr Stream.cons Stream.nil [1..3]
153-- To create a stream from monadic actions in a 'Foldable' container just use a
154-- right fold using 'consM' and 'nil':
156-- >>> Stream.drain $ Prelude.foldr (|:) Stream.nil [putStr "Hello ", putStrLn "world!"]
159-- For more ways to construct a stream see the module "Streamly.Prelude".
163-- We have already seen 'drain' and toList to eliminate a stream in the
164-- examples above. 'drain' runs a stream discarding the results i.e. only
165-- for effects. 'toList' runs the stream and collects the results in a list.
167-- For other ways to eliminate a stream see the @Folding@ section in
168-- "Streamly.Prelude" module.
172-- Transformation over a stream is the equivalent of a @for@ loop construct in
173-- imperative paradigm. We iterate over every element in the stream and perform
174-- certain transformations for each element. Transformations may involve
175-- mapping functions over the elements, filtering elements from the stream or
176-- folding all the elements in the stream into a single value. Streamly streams
177-- are exactly like lists and you can perform all the transformations in the
178-- same way as you would on lists.
180-- Here is a simple console echo program that just echoes every input line,
185-- Stream.repeatM getLine
186-- & Stream.mapM putStrLn
190-- The following code snippet reads lines from standard input, filters blank
191-- lines, drops the first non-blank line, takes the next two, up cases them,
192-- numbers them and prints them:
194-- >>> import Data.Char (toUpper)
197-- Stream.repeatM getLine
198-- & Stream.filter (not . null)
201-- & fmap (map toUpper)
202-- & Stream.zipWith (\n s -> show n ++ " " ++ s) (Stream.fromFoldable [1..])
203-- & Stream.mapM putStrLn
210-- We can combine two streams into a single stream using semigroup composition
211-- operation '<>'. Streams can be combined in many different ways as described
212-- in the following sections, the '<>' operation behaves differently depending
213-- on the stream type in effect. The stream type and therefore the composition
214-- style can be changed at any point using one of the type combinators as
219-- The 'Semigroup' operation '<>' of the 'Serial' type combines the two streams
220-- in a /serial depth first/ manner. We use the 'fromSerial' type combinator to
221-- effect 'Serial' style of composition. We can also use an explicit 'Serial'
222-- type annotation for the stream to achieve the same effect. However, since
223-- 'Serial' is the default type unless explicitly specified by using a
224-- combinator, we can omit using an explicit combinator or type annotation for
225-- this style of composition.
227-- When two streams with multiple elements are combined in this manner, the
228-- monadic actions in the two streams are performed sequentially i.e. first all
229-- actions in the first stream are performed sequentially and then all actions
230-- in the second stream are performed sequentially. We call it
231-- /serial depth first/ as the full depth of one stream is fully traversed
232-- before we move to the next. The following example prints the sequence 1, 2,
235-- >>> stream1 = print 1 |: print 2 |: Stream.nil
236-- >>> stream2 = print 3 |: print 4 |: Stream.nil
237-- >>> Stream.drain $ stream1 <> stream2
243-- All actions in both the streams are performed serially in the same thread.
245-- The polymorphic version of the binary operation '<>' of the 'Serial' type is
246-- 'serial'. We can use 'serial' to join streams in a sequential manner
247-- irrespective of the type of stream:
249-- >>> Stream.drain $ stream1 `Stream.serial` stream2
258-- The 'Semigroup' operation '<>' of the 'WSerial' type combines the two
259-- streams in a /serial breadth first/ manner. We use the fromWSerial type
260-- combinator to effect 'WSerial' style of composition. We can also use the
261-- 'WSerial' type annotation for the stream to achieve the same effect.
263-- When two streams with multiple elements are combined in this manner, we
264-- traverse all the streams in a breadth first manner i.e. one action from each
265-- stream is performed and yielded to the resulting stream before we come back
266-- to the first stream again and so on.
267-- The following example prints the sequence 1, 3, 2, 4
269-- >>> stream1 = print 1 |: print 2 |: Stream.nil
270-- >>> stream2 = print 3 |: print 4 |: Stream.nil
271-- >>> Stream.drain $ Stream.fromWSerial $ stream1 <> stream2
277-- Even though the monadic actions of the two streams are performed in an
278-- interleaved manner they are all performed serially in the same thread.
280-- The polymorphic version of the 'WSerial' binary operation '<>' is called
281-- 'wSerial'. We can use 'wSerial' to join streams in an interleaved manner
282-- irrespective of the type, notice that we have not used the fromWSerial
283-- combinator in the following example:
285-- >>> Stream.drain $ stream1 `Stream.wSerial` stream2
291-- Note that this composition cannot be used to fold infinite number of streams
292-- since it requires preserving the state until a stream is finished.
296-- We can use 'Monoid' instances to fold a container of streams in the desired
297-- style using 'fold' or 'foldMap'. We have also provided some fold utilities
298-- to fold streams using the polymorphic combine operations:
300-- * 'concatFoldableWith' is like 'fold', it folds a 'Foldable' container of
301-- streams using the given composition operator.
302-- * 'concatMapFoldableWith' is like 'foldMap', it folds like
303-- @concatFoldableWith@ but also maps a function before folding.
304-- * 'concatForFoldableWith' is like @concatMapFoldableWith@ but the container
305-- argument comes before the function argument.
307-- All of the following are equivalent:
310-- traced = Stream.fromEffect . print
312-- Stream.drain $ foldMap traced [1..10]
313-- Stream.drain $ Stream.concatFoldableWith Stream.serial (map traced [1..10])
314-- Stream.drain $ Stream.concatMapFoldableWith Stream.serial traced [1..10]
315-- Stream.drain $ Stream.concatForFoldableWith Stream.serial [1..10] traced
321-- Till now we discussed ways to apply transformations on a stream or to merge
322-- streams together to create another stream. We mentioned earlier that
323-- transforming a stream is similar to a @for@ loop in the imperative paradigm.
324-- We will now discuss the concept of a nested composition of streams which is
325-- analogous to nested @for@ loops in the imperative paradigm. Functional
326-- programmers call this style of composition a list transformer or @ListT@.
327-- Logic programmers call it a logic monad or non-deterministic composition,
328-- but for ordinary imperative minded people like me it is easier to think in
329-- terms of good old nested @for@ loops.
333-- In functional programmer's parlance the 'Monad' instances of different
334-- 'IsStream' types implement non-determinism, exploring all possible
335-- combination of choices from both the streams. From an imperative
336-- programmer's point of view it behaves like nested loops i.e. for each
337-- element in the first stream and for each element in the second stream
338-- execute the body of the loop.
340-- The 'Monad' instances of 'Serial', 'WSerial', 'Async' and 'WAsync'
341-- stream types support different flavors of nested looping. In other words,
342-- they are all variants of list transformer. The nesting behavior of these
343-- types correspond exactly to the way they merge streams as we discussed in
344-- the previous section.
349-- The 'Monad' composition of the 'CrossStream' type behaves like a standard list
352-- Let's start with an example with a simple @for@ loop without any nesting.
353-- For simplicity of illustration we are using streams of pure values in all
354-- the examples. However, the streams could also be made of monadic actions
358-- Stream.drain $ unCrossStream $ do
359-- x <- CrossStream (Stream.fromFoldable [3,2,1])
360-- CrossStream (Stream.fromEffect $ print x)
366-- As we can see, the code after the @fromFoldable@ statement is run three
367-- times, once for each value of @x@ drawn from the stream. All the three
368-- iterations are serial and run in the same thread one after another. In
369-- imperative terms this is equivalent to a @for@ loop with three iterations.
371-- We can write the console echo program that we wrote earlier using the monad
376-- Stream.drain $ unCrossStream $ do
377-- x <- CrossStream (Stream.repeatM getLine)
378-- CrossStream (Stream.fromEffect $ putStrLn x)
381-- When multiple streams are composed using this style they nest in a DFS
385-- Stream.drain $ unCrossStream $ do
386-- x <- CrossStream (Stream.fromFoldable [1,2])
387-- y <- CrossStream (Stream.fromFoldable [3,4])
388-- CrossStream (Stream.fromEffect $ print (x, y))
395-- i.e. inner loop iterations ((1,3), (1,4)) are executed before we proceed to
396-- the next iteration of the outer loop ((2,3), (2,4)). This behaves just like
397-- nested @for@ loops in imperative programming.
399-- Notice that this is analogous to merging streams of type 'Serial' or merging
400-- streams using 'serial'.
402-- $interleavedNesting
404-- TBD: generate the WSerial type using the TH utils.
406-- The 'Monad' composition of 'WSerial' type interleaves the iterations of
407-- outer and inner loops in a nested loop composition.
410-- Stream.drain $ getWSerial $ do
411-- x <- WSerialStream (Stream.fromFoldable [1,2])
412-- y <- WSerialStream (Stream.fromFoldable [3,4])
413-- WSerialStream (Stream.fromEffect $ print (x, y))
420-- Note that (2,3) is preferred to (1,4). This works exactly the same way as
421-- the merging of two streams using 'wSerial' works.
423-- The fromWSerial type combinator can be used to switch to this style of
424-- composition. Alternatively, a type annotation can be used to specify the
425-- type of the stream as 'WSerial'.
431-- composed :: Stream IO ()
432-- composed = unCrossStream $ do
433-- sz <- CrossStream sizes
434-- cl <- CrossStream colors
435-- sh <- CrossStream shapes
436-- CrossStream (Stream.fromEffect $ print (sz, cl, sh))
438-- sizes = Stream.fromFoldable [1, 2, 3]
439-- colors = Stream.fromFoldable ["red", "green", "blue"]
440-- shapes = Stream.fromFoldable ["triangle", "square", "circle"]
446-- 'fmap' transforms a stream by mapping a function on all elements of the
447-- stream. 'fmap' behaves in the same way for all stream types, it is always
450-- >>> (Stream.toList $ fmap show $ Stream.fromFoldable [1..10]) >>= print
451-- ["1","2","3","4","5","6","7","8","9","10"]
453-- Also see functions 'mapM' and 'sequence' from "Streamly.Prelude" module
454-- which can map actions concurrently depending on the type of the input stream.
458-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
459-- zipping applicatives separate types 'ZipStream' and 'ZipAsync' are
462-- The following is an example of 'CrossStream' applicative, it runs all iterations
465-- >>> p n = Stream.fromEffect (print n >> pure n)
466-- >>> s1 = p 1 <> p 2
467-- >>> s2 = p 3 <> p 4
469-- >>> (Stream.toList $ unCrossStream $ (,) <$> CrossStream s1 <*> CrossStream s2) >>= print
476-- [(1,3),(1,4),(2,3),(2,4)]
478-- Similarly, 'WSerial' applicative runs the iterations in an interleaved
479-- order but being serial it too takes a total of 17 seconds:
481-- >> (Stream.toList $ Stream.WSerialStream $ (,) <$> WSerialStream s1 <*> WSerialStream s2) >>= print
488-- [(1,3),(2,3),(1,4),(2,4)]
492-- Zipping is a special transformation where the corresponding elements of two
493-- streams are combined together using a zip function producing a new stream of
494-- outputs. Two different types are provided for serial and concurrent zipping.
495-- These types provide an applicative instance that can be used to lift
496-- functions to zip the argument streams.
497-- Also see the zipping functions in the "Streamly.Prelude" module.
501-- The applicative instance of 'ZipSerial' type zips streams serially.
502-- 'fromZipSerial' type combinator can be used to switch to serial applicative
505-- >>> p n = Stream.fromEffect (print n >> pure n)
506-- >>> s1 = Stream.fromSerial $ p 1 <> p 2
507-- >>> s2 = Stream.fromSerial $ p 3 <> p 4
508-- >>> (Stream.toList $ Stream.fromZipSerial $ (,) <$> s1 <*> s2) >>= print
518-- * Read the concurrent streams tutorial
519-- * See the examples in <https://github.com/composewell/streamly-examples streamly-examples> repo.
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