1{-# OPTIONS_GHC -fno-warn-unused-imports #-}
3-- Module : Streamly.Tutorial
4-- Copyright : (c) 2017 Harendra Kumar
7-- Maintainer : harendra.kumar@gmail.com
9-- Streamly, short for stream concurrently, combines the essence of
10-- non-determinism, streaming and concurrency in functional programming.
11-- Concurrent and non-concurrent applications are almost indistinguisable,
12-- concurrency capability does not at all impact the performance of
13-- non-concurrent case.
14-- Streaming enables writing modular, composable and scalable applications with
15-- ease and concurrency allows you to make them scale and perform well.
16-- Streamly enables writing concurrent applications without being aware of
17-- threads or synchronization. No explicit thread control is needed, where
18-- applicable the concurrency rate is automatically controlled based on the
19-- demand by the consumer. However, combinators are provided to fine tune the
20-- concurrency control.
21-- Streaming and concurrency together enable expressing reactive applications
22-- conveniently. See "Streamly.Examples" for a simple SDL based FRP example.
24-- Streamly streams are very much like the Haskell lists and most of the
25-- functions that work on lists have a counterpart that works on streams.
26-- However, streamly streams can be generated, consumed or combined
27-- concurrently. In this tutorial we will go over the basic concepts and how to
28-- use the library. The documentation of @Streamly@ module has more details on
29-- core APIs. For more APIs for constructing, folding, filtering, mapping and
30-- zipping etc. see the documentation of "Streamly.Prelude" module. For
31-- examples and other ways to use the library see the module
32-- "Streamly.Examples" as well.
34module Streamly.Tutorial
39 -- ** Generating Streams
42 -- ** Eliminating Streams
45 -- * Combining Streams
51 -- *** Serial composition ('<>')
54 -- *** Async composition ('<|')
57 -- *** Interleaved composition ('<=>')
60 -- *** Fair Concurrent composition ('<|>')
63 -- *** Custom composition
69 -- * Transforming Streams
75 -- *** Serial Composition ('StreamT')
78 -- *** Async Composition ('AsyncT')
81 -- *** Interleaved Composition ('InterleavedT')
82 -- $interleavedNesting
84 -- *** Fair Concurrent Composition ('ParallelT')
85 -- $fairlyConcurrentNesting
102 -- ** Parallel Zipping
105 -- * Summary of Compositions
106 -- $compositionSummary
108 -- * Concurrent Programming
111 -- * Reactive Programming
117 -- * Interoperation with Streaming Libraries
120 -- * Comparison with Existing Packages
126import Streamly.Prelude
128import Control.Applicative
130import Control.Monad.IO.Class (MonadIO(..))
131import Control.Monad.Trans.Class (MonadTrans (lift))
135-- Streamly provides many different stream types depending on the desired
136-- composition style. The simplest type is 'StreamT'. 'StreamT' is a monad
137-- transformer, the type @StreamT m a@ represents a stream of values of type
138-- 'a' in some underlying monad 'm'. For example, @StreamT IO Int@ is a stream
139-- of 'Int' in 'IO' monad.
143-- Pure values can be placed into the stream type using 'return' or 'pure'.
144-- Effects in the IO monad can be lifted to the stream type using the 'liftIO'
145-- combinator. In a transformer stack we can lift actions from the lower monad
146-- using the 'lift' combinator. Some examples of streams with a single element:
149-- return 1 :: 'StreamT' IO Int
152-- liftIO $ putStrLn "Hello world!" :: 'StreamT' IO ()
155-- We can combine streams using '<>' to create streams of many elements:
158-- return 1 <> return 2 <> return 3 :: 'StreamT' IO Int
161-- For more ways to construct or generate a stream see the module
162-- "Streamly.Prelude".
166-- 'runStreamT' runs a composed 'StreamT' computation, lowering the type into
167-- the underlying monad and discarding the result stream:
172-- main = 'runStreamT' $ liftIO $ putStrLn "Hello world!"
175-- 'toList' runs a stream computation and collects the result stream in a list
176-- in the underlying monad. 'toList' is a polymorphic function that works on
177-- multiple stream types belonging to the class 'Streaming'. Therefore, before
178-- you run a stream you need to tell how you want to interpret the stream by
179-- using one of the stream type combinators ('serially', 'asyncly', 'parallely'
180-- etc.). The combinator 'serially' is equivalent to annotating the type as @::
185-- import "Streamly.Prelude"
188-- xs \<- 'toList' $ 'serially' $ return 1 <> return 2
192-- For other ways to eliminate or fold a stream see the module
193-- "Streamly.Prelude".
196-- Streams of the same type can be combined into a composite stream in many
197-- different ways using one of the semigroup style binary composition operators
198-- i.e. '<>', '<=>', '<|', '<|>', 'mplus'. These operators work on all stream
199-- types ('StreamT', 'AsyncT' etc.) uniformly.
201-- To illustrate the concurrent aspects, we will use the following @delay@
202-- function to introduce a delay specified in seconds.
206-- import Control.Concurrent
208-- delay n = liftIO $ do
209-- threadDelay (n * 1000000)
211-- putStrLn (show tid ++ ": Delay " ++ show n)
216-- We have already seen, the '<>' operator. It composes two streams in series
217-- i.e. the first stream is completely exhausted and then the second stream is
218-- processed. The following example prints the sequence 3, 2, 1 and takes a
219-- total of 6 seconds because everything is serial:
222-- main = 'runStreamT' $ delay 3 <> delay 2 <> delay 1
225-- ThreadId 36: Delay 3
226-- ThreadId 36: Delay 2
227-- ThreadId 36: Delay 1
231-- The '<=>' operator is serial like '<>' but it interleaves the two streams
232-- i.e. it yields one element from the first stream and then one element from
233-- the second stream, and so on. The following example prints the sequence 1,
234-- 3, 2, 4 and takes a total of 10 seconds because everything is serial:
237-- main = 'runStreamT' $ (delay 1 <> delay 2) '<=>' (delay 3 <> delay 4)
240-- ThreadId 36: Delay 1
241-- ThreadId 36: Delay 3
242-- ThreadId 36: Delay 2
243-- ThreadId 36: Delay 4
246-- Note that this operator cannot be used to fold infinite containers since it
247-- requires preserving the state until a stream is finished. To be clear, it
248-- can combine infinite streams but not infinite number of streams.
252-- The '<|' operator can run both computations concurrently, /when needed/.
253-- In the following example since the first computation blocks we start the
254-- next one in a separate thread and so on:
257-- main = 'runStreamT' $ delay 3 '<|' delay 2 '<|' delay 1
260-- ThreadId 42: Delay 1
261-- ThreadId 41: Delay 2
262-- ThreadId 40: Delay 3
265-- This is the concurrent version of the '<>' operator. The computations are
266-- triggered in the same order as '<>' except that they are concurrent. When
267-- we have a tree of computations composed using this operator, the tree is
268-- traversed in DFS style just like '<>'.
271-- main = 'runStreamT' $ (p 1 '<|' p 2) '<|' (p 3 '<|' p 4)
272-- where p = liftIO . print
281-- Concurrency provided by this operator is demand driven. The second
282-- computation is run concurrently with the first only if the first computation
283-- is not producing enough output to keep the stream consumer busy otherwise
284-- the second computation is run serially after the previous one. The number of
285-- concurrent threads is adapted dynamically based on the pull rate of the
286-- consumer of the stream.
287-- As you can see, in the following example the computations are run in a
288-- single thread one after another, because none of them blocks. However, if
289-- the thread consuming the stream were faster than the producer then it would
290-- have started parallel threads for each computation to keep up even if none
294-- main = 'runStreamT' $ traced (sqrt 9) '<|' traced (sqrt 16) '<|' traced (sqrt 25)
302-- Since the concurrency provided by this operator is demand driven it cannot
303-- be used when the composed computations have timers that are relative to each
304-- other because all computations may not be started at the same time and
305-- therefore timers in all of them may not start at the same time. When
306-- relative timing among all computations is important or when we need to start
307-- all computations at once for some reason '<|>' must be used instead.
308-- However, '<|' is useful in situations when we want to optimally utilize the
309-- resources and we know that the computations can run in parallel but we do
310-- not care if they actually run in parallel or not, that decision is left to
311-- the scheduler. Also, note that this operator can be used to fold infinite
312-- containers in contrast to '<|>', because it does not require us to run all
313-- of them at the same time.
315-- The left bias (or the DFS style) of the operator '<|' is suggested by its
316-- shape. You can also think of this as an unbalanced version of the fairly
317-- parallel operator '<|>'.
321-- The 'Alternative' composition operator '<|>', like '<|', runs the composed
322-- computations concurrently. However, unlike '<|' it runs all of the
323-- computations in fairly parallel manner using a round robin scheduling
324-- mechanism. This can be considered as the concurrent version of the fairly
325-- interleaved serial operation '<=>'. Note that this cannot be used on
326-- infinite containers, as it will lead to an infinite sized scheduling queue.
328-- The following example sends a query to three search engines in parallel and
329-- prints the name of the search engine as a response arrives:
333-- import Network.HTTP.Simple
335-- main = 'runStreamT' $ google \<|> bing \<|> duckduckgo
337-- google = get "https://www.google.com/search?q=haskell"
338-- bing = get "https://www.bing.com/search?q=haskell"
339-- duckduckgo = get "https://www.duckduckgo.com/?q=haskell"
340-- get s = liftIO (httpNoBody (parseRequest_ s) >> putStrLn (show s))
345-- The 'async' API can be used to create references to asynchronously running
346-- stream computations. We can then use 'uncons' to explore the streams
347-- arbitrarily and then recompose individual elements to create a new stream.
348-- This way we can dynamically decide which stream to explore at any given
349-- time. Take an example of a merge sort of two sorted streams. We need to
350-- keep consuming items from the stream which has the lowest item in the sort
351-- order. This can be achieved using async references to streams. See
352-- "Streamly.Examples.MergeSortedStreams".
356-- Each of the semigroup compositions described has an identity that can be
357-- used to fold a possibly empty container. An empty stream is represented by
358-- 'nil' which can be represented in various standard forms as 'mempty',
359-- 'empty' or 'mzero'.
360-- Some fold utilities are also provided by the library for convenience:
362-- * 'foldWith' folds a 'Foldable' container of stream computations using the
363-- given composition operator.
364-- * 'foldMapWith' folds like foldWith but also maps a function before folding.
365-- * 'forEachWith' is like foldMapwith but the container argument comes before
366-- the function argument.
367-- * The 'each' primitive from "Streamly.Prelude" folds a 'Foldable' container
368-- using the '<>' operator:
370-- All of the following are equivalent:
374-- import "Streamly.Prelude"
377-- 'toList' . 'serially' $ 'foldWith' (<>) (map return [1..10]) >>= print
378-- 'toList' . 'serially' $ 'foldMapWith' (<>) return [1..10] >>= print
379-- 'toList' . 'serially' $ 'forEachWith' (<>) [1..10] return >>= print
380-- 'toList' . 'serially' $ 'each' [1..10] >>= print
385-- The previous section discussed ways to merge the elements of two streams
386-- without doing any transformation on them. In this section we will explore
387-- how to transform streams using 'Functor', 'Applicative' or 'Monad' style
388-- compositions. The applicative and monad composition of all 'Streaming' types
389-- behave exactly the same way as a list transformer. For simplicity of
390-- illustration we are using streams of pure values in the following examples.
391-- However, the real application of streams arises when these streams are
392-- generated using monadic actions.
396-- In functional programmer's parlance the 'Monad' instance of 'Streaming'
397-- types implement non-determinism, exploring all possible combination of
398-- choices from both the streams. From an imperative programmer's point of view
399-- it behaves like nested loops i.e. for each element in the first stream and
400-- for each element in the second stream apply the body of the loop. If you are
401-- familiar with list transformer this behavior is exactly the same as that of
402-- a list transformer.
404-- Just like we saw in sum style compositions earlier, monadic composition also
405-- has multiple variants each of which exactly corresponds to one of the sum
406-- style composition variant.
410-- When we interpret the monadic composition as 'StreamT' we get a standard
411-- list transformer like serial composition.
415-- import "Streamly.Prelude"
417-- main = 'runStreamT' $ do
418-- x <- 'each' [3,2,1]
422-- ThreadId 30: Delay 3
423-- ThreadId 30: Delay 2
424-- ThreadId 30: Delay 1
427-- As you can see the code after the @each@ statement is run three times, once
428-- for each value of @x@. All the three iterations are serial and run in the
429-- same thread one after another. When compared to imperative programming, this
430-- can also be viewed as a @for@ loop with three iterations.
432-- A console echo loop copying standard input to standard output can simply be
437-- import Data.Semigroup (cycle1)
439-- main = 'runStreamT' $ cycle1 (liftIO getLine) >>= liftIO . putStrLn
442-- When multiple streams are composed using this style they nest in a DFS
443-- manner i.e. nested iterations of an iteration are executed before we proceed
444-- to the next iteration at higher level. This behaves just like nested @for@
445-- loops in imperative programming.
449-- import "Streamly.Prelude"
451-- main = 'runStreamT' $ do
454-- liftIO $ putStrLn $ show (x, y)
463-- You will also notice that this is the monadic equivalent of the sum style
464-- composition using '<>'.
468-- When we interpret the monadic composition as 'AsyncT' we get a /concurrent/
469-- list-transformer like composition. Multiple monadic continuations (or loop
470-- iterations) may be started concurrently. Concurrency is demand driven
471-- i.e. more concurrent iterations are started only if the previous iterations
472-- are not able to produce enough output for the consumer of the output stream.
473-- This is the concurrent version of 'StreamT'.
477-- import "Streamly.Prelude"
479-- main = 'runAsyncT' $ do
480-- x <- 'each' [3,2,1]
484-- ThreadId 40: Delay 1
485-- ThreadId 39: Delay 2
486-- ThreadId 38: Delay 3
489-- As you can see the code after the @each@ statement is run three times, once
490-- for each value of @x@. All the three iterations are concurrent and run in
491-- different threads. The iteration with least delay finishes first. When
492-- compared to imperative programming, this can be viewed as a @for@ loop
493-- with three concurrent iterations.
495-- Concurrency is demand driven just as in the case of '<|'. When multiple
496-- streams are composed using this style the iterations are triggered in a DFS
497-- manner just like 'StreamT' i.e. nested iterations are executed before we
498-- proceed to the next iteration at higher level. However, unlike 'StreamT'
499-- more than one iterations may be started concurrently, and based on the
500-- demand from the consumer.
504-- import "Streamly.Prelude"
506-- main = 'runAsyncT' $ do
509-- liftIO $ putStrLn $ show (x, y)
518-- You will notice that this is the monadic equivalent of the '<|' style
519-- sum composition. The same caveats apply to this as the '<|' operation.
521-- $interleavedNesting
523-- When we interpret the monadic composition as 'InterleavedT' we get a serial
524-- but fairly interleaved list-transformer like composition. The monadic
525-- continuations or iterations of the outer loop are fairly interleaved with
526-- the continuations or iterations of the inner loop.
530-- import "Streamly.Prelude"
532-- main = 'runInterleavedT' $ do
535-- liftIO $ putStrLn $ show (x, y)
544-- You will notice that this is the monadic equivalent of the '<=>' style
545-- sum composition. The same caveats apply to this as the '<=>' operation.
547-- $fairlyConcurrentNesting
549-- When we interpret the monadic composition as 'ParallelT' we get a
550-- /concurrent/ list-transformer like composition just like 'AsyncT'. The
551-- difference is that this is fully parallel with all iterations starting
552-- concurrently instead of the demand driven concurrency of 'AsyncT'.
556-- import "Streamly.Prelude"
558-- main = 'runParallelT' $ do
559-- x <- 'each' [3,2,1]
563-- ThreadId 40: Delay 1
564-- ThreadId 39: Delay 2
565-- ThreadId 38: Delay 3
568-- You will notice that this is the monadic equivalent of the '<|>' style
569-- sum composition. The same caveats apply to this as the '<|>' operation.
573-- The streamly code is usually written in a way that is agnostic of the
574-- specific monadic composition type. We use a polymorphic type with a
575-- 'Streaming' type class constraint. When running the stream we can choose the
576-- specific mode of composition. For example look at the following code.
580-- import "Streamly.Prelude"
583-- composed :: 'Streaming' t => t m a
588-- liftIO $ putStrLn $ show (sz, cl, sh)
592-- sizes = 'each' [1, 2, 3]
593-- colors = 'each' ["red", "green", "blue"]
594-- shapes = 'each' ["triangle", "square", "circle"]
597-- Now we can interpret this in whatever way we want:
600-- main = 'runStreamT' composed
601-- main = 'runAsyncT' composed
602-- main = 'runInterleavedT' composed
603-- main = 'runParallelT' composed
606-- Equivalently, we can also write it using the type adapter combinators, like
610-- main = 'runStreaming' $ 'serially' $ composed
611-- main = 'runStreaming' $ 'asyncly' $ composed
612-- main = 'runStreaming' $ 'interleaving' $ composed
613-- main = 'runStreaming' $ 'parallely' $ composed
616-- As an exercise try to figure out the output of this code for each mode of
621-- 'fmap' transforms a stream by mapping a function on all elements of the
622-- stream. The functor instance of each stream type defines 'fmap' to be
623-- precisely the same as 'liftM', and therefore 'fmap' is always serial
624-- irrespective of the type. For concurrent mapping, alternative versions of
625-- 'fmap', namely, 'asyncMap' and 'parMap' are provided.
630-- main = ('toList' $ 'serially' $ fmap show $ 'each' [1..10]) >>= print
633-- Also see the 'mapM' and 'sequence' functions for mapping actions, in the
634-- "Streamly.Prelude" module.
638-- Applicative is precisely the same as the 'ap' operation of 'Monad'. For
639-- zipping and parallel applicatives separate types 'ZipStream' and 'ZipAsync'
642-- The following example runs all iterations serially and takes a total 17
643-- seconds (1 + 3 + 4 + 2 + 3 + 4):
647-- import "Streamly.Prelude"
648-- import Control.Concurrent
652-- d n = delay n >> return n
654-- main = ('toList' . 'serially' $ (,) \<$> s1 \<*> s2) >>= print
657-- ThreadId 36: Delay 1
658-- ThreadId 36: Delay 3
659-- ThreadId 36: Delay 4
660-- ThreadId 36: Delay 2
661-- ThreadId 36: Delay 3
662-- ThreadId 36: Delay 4
663-- [(1,3),(1,4),(2,3),(2,4)]
666-- Similalrly interleaving runs the iterations in an interleaved order but
667-- since it is serial it takes a total of 17 seconds:
670-- main = ('toList' . 'interleaving' $ (,) \<$> s1 \<*> s2) >>= print
673-- ThreadId 36: Delay 1
674-- ThreadId 36: Delay 3
675-- ThreadId 36: Delay 2
676-- ThreadId 36: Delay 3
677-- ThreadId 36: Delay 4
678-- ThreadId 36: Delay 4
679-- [(1,3),(2,3),(1,4),(2,4)]
682-- 'AsyncT' can run the iterations concurrently and therefore takes a total
683-- of 10 seconds (1 + 2 + 3 + 4):
686-- main = ('toList' . 'asyncly' $ (,) \<$> s1 \<*> s2) >>= print
689-- ThreadId 34: Delay 1
690-- ThreadId 36: Delay 2
691-- ThreadId 35: Delay 3
692-- ThreadId 36: Delay 3
693-- ThreadId 35: Delay 4
694-- ThreadId 36: Delay 4
695-- [(1,3),(2,3),(1,4),(2,4)]
698-- Similalrly 'ParallelT' as well can run the iterations concurrently and
699-- therefore takes a total of 10 seconds (1 + 2 + 3 + 4):
702-- main = ('toList' . 'parallely' $ (,) \<$> s1 \<*> s2) >>= print
705-- ThreadId 34: Delay 1
706-- ThreadId 36: Delay 2
707-- ThreadId 35: Delay 3
708-- ThreadId 36: Delay 3
709-- ThreadId 35: Delay 4
710-- ThreadId 36: Delay 4
711-- [(1,3),(2,3),(1,4),(2,4)]
714-- $compositionSummary
716-- The following table summarizes the types for monadic compositions and the
717-- operators for sum style compositions. This table captures the essence of
721-- +-----+--------------+------------+
722-- | | Serial | Concurrent |
723-- +=====+==============+============+
724-- | DFS | 'StreamT' | 'AsyncT' |
725-- | +--------------+------------+
727-- +-----+--------------+------------+
728-- | BFS | 'InterleavedT' | 'ParallelT' |
729-- | +--------------+------------+
730-- | | '<=>' | '<|>' |
731-- +-----+--------------+------------+
736-- Zipping is a special transformation where the corresponding elements of two
737-- streams are combined together using a zip function producing a new stream of
738-- outputs. Two different types are provided for serial and concurrent zipping.
739-- These types provide an applicative instance that zips the argument streams.
740-- Also see the zipping function in the "Streamly.Prelude" module.
744-- 'ZipStream' zips streams serially:
748-- import "Streamly.Prelude"
749-- import Control.Concurrent
751-- d n = delay n >> return n
752-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
753-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
755-- main = ('toList' . 'zipping' $ (,) \<$> s1 \<*> s2) >>= print
758-- This takes total 10 seconds to zip, which is (1 + 2 + 3 + 4) since
759-- everything runs serially:
762-- ThreadId 29: Delay 1
763-- ThreadId 29: Delay 3
764-- ThreadId 29: Delay 2
765-- ThreadId 29: Delay 4
771-- 'ZipAsync' zips streams concurrently:
775-- import "Streamly.Prelude"
776-- import Control.Concurrent
777-- import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
779-- d n = delay n >> return n
780-- s1 = 'adapt' . 'serially' $ d 1 <> d 2
781-- s2 = 'adapt' . 'serially' $ d 3 <> d 4
784-- liftIO $ hSetBuffering stdout LineBuffering
785-- ('toList' . 'zippingAsync' $ (,) \<$> s1 \<*> s2) >>= print
788-- This takes 7 seconds to zip, which is max (1,3) + max (2,4) because 1 and 3
789-- are produced concurrently, and 2 and 4 are produced concurrently:
792-- ThreadId 32: Delay 1
793-- ThreadId 32: Delay 2
794-- ThreadId 33: Delay 3
795-- ThreadId 33: Delay 4
801-- When writing concurrent programs there are two distinct places where the
802-- programmer chooses the type of concurrency. First, when /generating/ a
803-- stream by combining other streams we can use one of the sum style operators
804-- to combine them concurrently or serially. Second, when /processing/ a stream
805-- in a monadic composition we can choose one of the monad composition types to
806-- choose the desired type of concurrency.
808-- In the following example the squares of @x@ and @y@ are computed
809-- concurrently using the '<|' operator and the square roots of their sum are
810-- also computed concurrently by using the 'asyncly' combinator. We can choose
811-- different combinators e.g. '<>' and 'serially', to control the concurrency.
815-- import "Streamly.Prelude" (toList)
816-- import Data.List (sum)
820-- $ 'asyncly' -- Concurrent monadic processing (sqrt below)
822-- x2 \<- 'forEachWith' ('<|') [1..100] $ -- Concurrent @"for"@ loop
823-- \\x -> return $ x * x -- body of the loop
824-- y2 \<- 'forEachWith' ('<|') [1..100] $
825-- \\y -> return $ y * y
826-- return $ sqrt (x2 + y2)
830-- You can see how this directly maps to the imperative style
831-- <https://en.wikipedia.org/wiki/OpenMP OpenMP> model, we use combinators
832-- and operators instead of the ugly pragmas.
834-- For more concurrent programming examples see,
835-- "Streamly.Examples.ListDirRecursive", "Streamly.Examples.MergeSortedStreams"
836-- and "Streamly.Examples.SearchEngineQuery".
840-- Reactive programming is nothing but concurrent streaming which is what
841-- streamly is all about. With streamly we can generate streams of events,
842-- merge streams that are generated concurrently and process events
843-- concurrently. We can do all this without any knowledge about the specifics
844-- of the implementation of concurrency. In the following example you will see
845-- that the code is just regular Haskell code without much streamly APIs used
846-- (active hyperlinks are the streamly APIs) and yet it is a reactive
850-- This application has two independent and concurrent sources of event
851-- streams, @acidRain@ and @userAction@. @acidRain@ continuously generates
852-- events that deteriorate the health of the game character. @userAction@ can
853-- be "potion" or "quit". When the user types "potion" the health improves and
854-- the game continues.
857-- {-\# LANGUAGE FlexibleContexts #-}
860-- import Control.Concurrent (threadDelay)
861-- import Control.Monad (when)
862-- import Control.Monad.State
863-- import Data.Semigroup (cycle1)
865-- data Event = Harm Int | Heal Int | Quit deriving (Show)
867-- userAction :: MonadIO m => 'StreamT' m Event
868-- userAction = cycle1 $ liftIO askUser
873-- "potion" -> return (Heal 10)
874-- "quit" -> return Quit
875-- _ -> putStrLn "What?" >> askUser
877-- acidRain :: MonadIO m => 'StreamT' m Event
878-- acidRain = cycle1 $ liftIO (threadDelay 1000000) >> return (Harm 1)
880-- game :: ('MonadAsync' m, MonadState Int m) => 'StreamT' m ()
882-- event \<- userAction \<|> acidRain
884-- Harm n -> modify $ \\h -> h - n
885-- Heal n -> modify $ \\h -> h + n
886-- Quit -> fail "quit"
889-- when (h <= 0) $ fail "You die!"
890-- liftIO $ putStrLn $ "Health = " ++ show h
893-- putStrLn "Your health is deteriorating due to acid rain,\\
894-- \\ type \\"potion\\" or \\"quit\\""
895-- _ <- runStateT ('runStreamT' game) 60
899-- You can also find the source of this example in
900-- "Streamly.Examples.AcidRainGame". It has been adapted from Gabriel's
901-- <https://hackage.haskell.org/package/pipes-concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html pipes-concurrency>
903-- This is much simpler compared to the pipes version because of the builtin
904-- concurrency in streamly. You can also find a SDL based reactive programming
905-- example adapted from Yampa in "Streamly.Examples.CirclingSquare".
909-- Streamly is highly optimized for performance, it is designed for serious
910-- high performing, concurrent and scalable applications. We have created the
911-- <https://hackage.haskell.org/package/streaming-benchmarks streaming-benchmarks>
912-- package which is specifically and carefully designed to measure the
913-- performance of Haskell streaming libraries fairly and squarely in the right
914-- way. Streamly performs at par or even better than most streaming libraries
915-- for common operations even though it needs to deal with the concurrency
920-- We can use @unfoldr@ and @uncons@ to convert one streaming type to another.
921-- We will assume the following common code to be available in the examples
922-- demonstrated below.
926-- import "Streamly.Prelude"
927-- import System.IO (stdin)
929-- -- Adapt uncons to return an Either instead of Maybe
930-- unconsE s = 'uncons' s >>= maybe (return $ Left ()) (return . Right)
931-- stdinLn = 'serially' $ 'fromHandle' stdin
934-- Interop with @pipes@:
937-- import qualified Pipes as P
938-- import qualified Pipes.Prelude as P
941-- -- streamly to pipe
942-- P.runEffect $ P.for (P.unfoldr unconsE stdinLn) (lift . putStrLn)
944-- -- pipe to streamly
945-- -- Adapt P.next to return a Maybe instead of Either
946-- let nextM p = P.next p >>= either (\\_ -> return Nothing) (return . Just)
947-- 'runStreamT' $ 'unfoldrM' nextM P.stdinLn >>= lift . putStrLn
950-- Interop with @streaming@:
953-- import qualified Streaming as S
954-- import qualified Streaming.Prelude as S
957-- -- streamly to streaming
958-- S.stdoutLn $ S.unfoldr unconsE stdinLn
960-- -- streaming to streamly
961-- 'runStreamT' $ unfoldrM S.uncons S.stdinLn >>= lift . putStrLn
965-- Interop with @conduit@:
968-- import qualified Data.Conduit as C
969-- import qualified Data.Conduit.List as C
970-- import qualified Data.Conduit.Combinators as C
972-- -- streamly to conduit
973-- main = (C.unfoldM 'uncons' stdinLn) C.$$ C.print
978-- Streamly unifies non-determinism, streaming, concurrency and FRP
979-- functionality that is otherwise covered by several disparate packages, and
980-- it does that with a surprisingly concise API. Here is a list of popular and
981-- well-known packages in all these areas:
984-- +-----------------+----------------+
985-- | Non-determinism | <https://hackage.haskell.org/package/list-t list-t> |
986-- | +----------------+
987-- | | <https://hackage.haskell.org/package/logict logict> |
988-- +-----------------+----------------+
989-- | Streaming | <https://hackage.haskell.org/package/streaming streaming> |
990-- | +----------------+
991-- | | <https://hackage.haskell.org/package/conduit conduit> |
992-- | +----------------+
993-- | | <https://hackage.haskell.org/package/pipes pipes> |
994-- | +----------------+
995-- | | <https://hackage.haskell.org/package/simple-conduit simple-conduit> |
996-- +-----------------+----------------+
997-- | Concurrency | <https://hackage.haskell.org/package/async async> |
998-- | +----------------+
999-- | | <https://hackage.haskell.org/package/transient transient> |
1000-- +-----------------+----------------+
1001-- | FRP | <https://hackage.haskell.org/package/Yampa Yampa> |
1002-- | +----------------+
1003-- | | <https://hackage.haskell.org/package/dunai dunai> |
1004-- | +----------------+
1005-- | | <https://hackage.haskell.org/package/reflex reflex> |
1006-- +-----------------+----------------+
1009-- Streamly covers all the functionality provided by both the non-determinism
1010-- packages listed above and provides better performance in comparison to
1011-- those. In fact, at the core streamly is a list transformer but it naturally
1012-- integrates the concurrency dimension to the basic list transformer
1015-- When it comes to streaming, in terms of core concepts, @simple-conduit@ is
1016-- the package that is closest to streamly if we set aside the concurrency
1017-- dimension, both are streaming packages with list transformer like monad
1018-- composition. However, in terms of API it is more like the @streaming@
1019-- package. Streamly can be used to achieve more or less the functionality
1020-- provided by any of the streaming packages listed above. The types and API of
1021-- streamly are much simpler in comparison to conduit and pipes. It is more or
1022-- less like the standard Haskell list APIs.
1024-- When it comes to concurrency, streamly can do everything that the @async@
1025-- package can do and more. async provides applicative concurrency whereas
1026-- streamly provides both applicative and monadic concurrency. The 'ZipAsync'
1027-- type behaves like the applicative instance of async. This work was
1028-- originally inspired by the concurrency implementation in @transient@ though
1029-- it has no resemblence with that. Streamly provides concurrency as transient
1030-- does but in a sort of dual manner, it can lazily stream the output. In
1031-- comparison to transient streamly has a first class streaming interface and
1032-- is a monad transformer that can be used universally in any Haskell monad
1033-- transformer stack.
1035-- The non-determinism, concurrency and streaming combination make streamly a
1036-- strong FRP capable library as well. FRP is fundamentally stream of events
1037-- that can be processed concurrently. The example in this tutorial as well as
1038-- the "Streamly.Examples.CirclingSquare" example from Yampa demonstrate the
1039-- basic FRP capability of streamly. In core concepts streamly is strikingly
1040-- similar to @dunai@. dunai was designed from a FRP perspective and streamly
1041-- wa original designed from a concurrency perspective. However, both have
1042-- similarity at the core.
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