on ec08681 help sign in
streamly/README.md
329 lines 12 kB history raw
1# Streamly
3[![Hackage](https://img.shields.io/hackage/v/streamly.svg?style=flat)](https://hackage.haskell.org/package/streamly)
4[![Gitter chat](https://badges.gitter.im/composewell/gitter.svg)](https://gitter.im/composewell/streamly)
5[![Build Status](https://travis-ci.org/composewell/streamly.svg?branch=master)](https://travis-ci.org/composewell/streamly)
6[![Windows Build status](https://ci.appveyor.com/api/projects/status/ajxg0c79raou9ned?svg=true)](https://ci.appveyor.com/project/harendra-kumar/streamly)
7[![Coverage Status](https://coveralls.io/repos/composewell/streamly/badge.svg?branch=master&service=github)](https://coveralls.io/github/composewell/streamly?branch=master)
9## Stream`ing` `Concurrent`ly
11Streamly, short for streaming concurrently, provides monadic streams, with a
12simple API, almost identical to standard lists, and an in-built support for
13concurrency. By using stream-style combinators on stream composition,
14streams can be generated, merged, chained, mapped, zipped, and consumed
15concurrently – providing a generalized high level programming framework
16unifying streaming and concurrency. Controlled concurrency allows even infinite
17streams to be evaluated concurrently. Concurrency is auto scaled based on
18feedback from the stream consumer. The programmer does not have to be aware of
19threads, locking or synchronization to write scalable concurrent programs.
21The basic streaming functionality of streamly is equivalent to that provided by
22streaming libraries like
23[vector](https://hackage.haskell.org/package/vector),
24[streaming](https://hackage.haskell.org/package/streaming),
25[pipes](https://hackage.haskell.org/package/pipes), and
26[conduit](https://hackage.haskell.org/package/conduit).
27In addition to providing streaming functionality, streamly subsumes
28the functionality of list transformer libraries like `pipes` or
29[list-t](https://hackage.haskell.org/package/list-t), and also the logic
30programming library [logict](https://hackage.haskell.org/package/logict). On
31the concurrency side, it subsumes the functionality of the
32[async](https://hackage.haskell.org/package/async) package. Because it supports
33streaming with concurrency we can write FRP applications similar in concept to
34[Yampa](https://hackage.haskell.org/package/Yampa) or
35[reflex](https://hackage.haskell.org/package/reflex).
37Why use streamly?
39 * _Simplicity_: Simple list like streaming API, if you know how to use lists
40 then you know how to use streamly. This library is built with simplicity
41 and ease of use as a design goal.
42 * _Concurrency_: Simple, powerful, and scalable concurrency. Concurrency is
43 built-in, and not intrusive, concurrent programs are written exactly the
44 same way as non-concurrent ones.
45 * _Generality_: Unifies functionality provided by several disparate packages
46 (streaming, concurrency, list transformer, logic programming, reactive
47 programming) in a concise API.
48 * _Performance_: Streamly is designed for high performance. It employs stream
49 fusion optimizations for best possible performance. Serial peformance is
50 equivalent to the venerable `vector` library in most cases and even better
51 in some cases. Concurrent performance is unbeatable. See
52 [streaming-benchmarks](https://github.com/composewell/streaming-benchmarks)
53 for a comparison of popular streaming libraries on micro-benchmarks.
55The following chart shows a summary of the cost of key streaming operations
56processing a million elements. The timings for streamly and vector are in the
57600-700 microseconds range and therefore can barely be seen in the graph.
59![Streaming Operations at a Glance](charts-0/KeyOperations-time.svg)
61For more details on streaming library ecosystem and where streamly fits in,
62please see
63[streaming libraries](https://github.com/composewell/streaming-benchmarks#streaming-libraries).
64Also, see the [Comparison with Existing
65Packages](https://hackage.haskell.org/package/streamly/docs/Streamly-Tutorial.html)
66section in the streamly tutorial.
68For more information on streamly, see:
70 * [Streamly.Tutorial](https://hackage.haskell.org/package/streamly/docs/Streamly-Tutorial.html) module in the haddock documentation for a detailed introduction
71 * [examples](https://github.com/composewell/streamly/tree/master/examples) directory in the package for some simple practical examples
73## Streaming Pipelines
75Unlike `pipes` or `conduit` and like `vector` and `streaming`, `streamly`
76composes stream data instead of stream processors (functions). A stream is
77just like a list and is explicitly passed around to functions that process the
78stream. Therefore, no special operator is needed to join stages in a streaming
79pipeline, just the standard function application (`$`) or reverse function
80application (`&`) operator is enough. Combinators are provided in
81`Streamly.Prelude` to transform or fold streams.
83The following snippet provides a simple stream composition example that reads
84numbers from stdin, prints the squares of even numbers and exits if an even
85number more than 9 is entered.
87```haskell
88import Streamly
89import qualified Streamly.Prelude as S
90import Data.Function ((&))
92main = runStream $
93 S.repeatM getLine
94 & fmap read
95 & S.filter even
96 & S.takeWhile (<= 9)
97 & fmap (\x -> x * x)
98 & S.mapM print
99```
101## Concurrent Stream Generation
103Monadic construction and generation functions e.g. `consM`, `unfoldrM`,
104`replicateM`, `repeatM`, `iterateM` and `fromFoldableM` etc. work concurrently
105when used with appropriate stream type combinator (e.g. `asyncly`, `aheadly` or
106`parallely`).
108The following code finishes in 3 seconds (6 seconds when serial):
110```
111> let p n = threadDelay (n * 1000000) >> return n
112> S.toList $ aheadly $ p 3 |: p 2 |: p 1 |: S.nil
113[3,2,1]
115> S.toList $ parallely $ p 3 |: p 2 |: p 1 |: S.nil
116[1,2,3]
117```
119The following finishes in 10 seconds (100 seconds when serial):
121```
122runStream $ asyncly $ S.replicateM 10 $ p 10
123```
125## Concurrent Streaming Pipelines
127Use `|&` or `|$` to apply stream processing functions concurrently. The
128following example prints a "hello" every second; if you use `&` instead of
129`|&` you will see that the delay doubles to 2 seconds instead because of serial
130application.
132```
133main = runStream $
134 S.repeatM (threadDelay 1000000 >> return "hello")
135 |& S.mapM (\x -> threadDelay 1000000 >> putStrLn x)
136```
138## Mapping Concurrently
140We can use `mapM` or `sequence` functions concurrently on a stream.
142```
143> let p n = threadDelay (n * 1000000) >> return n
144> runStream $ aheadly $ S.mapM (\x -> p 1 >> print x) (serially $ repeatM (p 1))
145```
147## Serial and Concurrent Merging
149Semigroup and Monoid instances can be used to fold streams serially or
150concurrently. In the following example we compose ten actions in the
151stream, each with a delay of 1 to 10 seconds, respectively. Since all the
152actions are concurrent we see one output printed every second:
154``` haskell
155import Streamly
156import qualified Streamly.Prelude as S
157import Control.Concurrent (threadDelay)
159main = S.toList $ parallely $ foldMap delay [1..10]
160 where delay n = S.yieldM $ threadDelay (n * 1000000) >> print n
161```
163Streams can be combined together in many ways. We provide some examples
164below, see the tutorial for more ways. We use the following `delay`
165function in the examples to demonstrate the concurrency aspects:
167``` haskell
168import Streamly
169import qualified Streamly.Prelude as S
170import Control.Concurrent
172delay n = S.yieldM $ do
173 threadDelay (n * 1000000)
174 tid <- myThreadId
175 putStrLn (show tid ++ ": Delay " ++ show n)
176```
177### Serial
179```haskell
180main = runStream $ delay 3 <> delay 2 <> delay 1
181```
182```
183ThreadId 36: Delay 3
184ThreadId 36: Delay 2
185ThreadId 36: Delay 1
186```
188### Parallel
190```haskell
191main = runStream . parallely $ delay 3 <> delay 2 <> delay 1
192```
193```
194ThreadId 42: Delay 1
195ThreadId 41: Delay 2
196ThreadId 40: Delay 3
197```
199## Nested Loops (aka List Transformer)
201The monad instance composes like a list monad.
203``` haskell
204import Streamly
205import qualified Streamly.Prelude as S
207loops = do
208 x <- S.fromFoldable [1,2]
209 y <- S.fromFoldable [3,4]
210 S.yieldM $ putStrLn $ show (x, y)
212main = runStream loops
213```
214```
215(1,3)
216(1,4)
217(2,3)
218(2,4)
219```
221## Concurrent Nested Loops
223To run the above code with, lookahead style concurrency i.e. each iteration in
224the loop can run run concurrently by but the results are presented in the same
225order as serial execution:
227``` haskell
228main = runStream $ aheadly $ loops
229```
231To run it with depth first concurrency yielding results asynchronously in the
232same order as they become available (deep async composition):
234``` haskell
235main = runStream $ asyncly $ loops
236```
238To run it with breadth first concurrency and yeilding results asynchronously
239(wide async composition):
241``` haskell
242main = runStream $ wAsyncly $ loops
243```
245The above streams provide lazy/demand-driven concurrency which is automatically
246scaled as per demand and is controlled/bounded so that it can be used on
247infinite streams. The following combinator provides strict, unbounded
248concurrency irrespective of demand:
250``` haskell
251main = runStream $ parallely $ loops
252```
254To run it serially but interleaving the outer and inner loop iterations
255(breadth first serial):
257``` haskell
258main = runStream $ wSerially $ loops
259```
261## Magical Concurrency
263Streams can perform semigroup (<>) and monadic bind (>>=) operations
264concurrently using combinators like `asyncly`, `parallelly`. For example,
265to concurrently generate squares of a stream of numbers and then concurrently
266sum the square roots of all combinations of two streams:
268``` haskell
269import Streamly
270import qualified Streamly.Prelude as S
272main = do
273 s <- S.sum $ asyncly $ do
274 -- Each square is performed concurrently, (<>) is concurrent
275 x2 <- foldMap (\x -> return $ x * x) [1..100]
276 y2 <- foldMap (\y -> return $ y * y) [1..100]
277 -- Each addition is performed concurrently, monadic bind is concurrent
278 return $ sqrt (x2 + y2)
279 print s
280```
282Of course, the actions running in parallel could be arbitrary IO actions. For
283example, to concurrently list the contents of a directory tree recursively:
285``` haskell
286import Path.IO (listDir, getCurrentDir)
287import Streamly
288import qualified Streamly.Prelude as S
290main = runStream $ aheadly $ getCurrentDir >>= readdir
291 where readdir d = do
292 (dirs, files) <- S.yieldM $ listDir d
293 S.yieldM $ mapM_ putStrLn $ map show files
294 -- read the subdirs concurrently, (<>) is concurrent
295 foldMap readdir dirs
296```
298In the above examples we do not think in terms of threads, locking or
299synchronization, rather we think in terms of what can run in parallel, the rest
300is taken care of automatically. When using `aheadly` the programmer does
301not have to worry about how many threads are to be created, they are
302automatically adjusted based on the demand of the consumer.
304The concurrency facilities provided by streamly can be compared with
305[OpenMP](https://en.wikipedia.org/wiki/OpenMP) and
306[Cilk](https://en.wikipedia.org/wiki/Cilk) but with a more declarative
307expression.
309## Reactive Programming (FRP)
311Streamly is a foundation for first class reactive programming as well by virtue
312of integrating concurrency and streaming. See
313[AcidRain.hs](https://github.com/composewell/streamly/tree/master/examples/AcidRain.hs)
314for a console based FRP game example and
315[CirclingSquare.hs](https://github.com/composewell/streamly/tree/master/examples/CirclingSquare.hs)
316for an SDL based animation example.
318## Contributing
320The code is available under BSD-3 license
321[on github](https://github.com/composewell/streamly). Join the
322[gitter chat](https://gitter.im/composewell/streamly) channel for discussions.
323You can find some of the
324[todo items on the github wiki](https://github.com/composewell/streamly/wiki/Things-To-Do).
325Please ask on the gitter channel or [contact the maintainer directly](mailto:harendra.kumar@gmail.com)
326for more details on each item. All contributions are welcome!
328This library was originally inspired by the `transient` package authored by
329Alberto G. Corona.