on 57fad21 help sign in
streamly/test/loops.hs
76 lines 2.6 kB history raw
1import Streamly
2import System.IO (stdout, hSetBuffering, BufferMode(LineBuffering))
3import Streamly.Prelude (nil, yieldM)
5main :: IO ()
6main = do
7 hSetBuffering stdout LineBuffering
9 putStrLn "\nloopTail:\n"
10 runStream $ do
11 x <- loopTail 0
12 yieldM $ print (x :: Int)
14 putStrLn "\nloopHead:\n"
15 runStream $ do
16 x <- loopHead 0
17 yieldM $ print (x :: Int)
19 putStrLn "\nloopTailA:\n"
20 runStream $ do
21 x <- loopTailA 0
22 yieldM $ print (x :: Int)
24 putStrLn "\nloopHeadA:\n"
25 runStream $ do
26 x <- loopHeadA 0
27 yieldM $ print (x :: Int)
29 putStrLn "\nwSerial:\n"
30 runStream $ do
31 x <- (return 0 <> return 1) `wSerial` (return 100 <> return 101)
32 yieldM $ print (x :: Int)
34 putStrLn "\nParallel interleave:\n"
35 runStream $ do
36 x <- (return 0 <> return 1) `wAsync` (return 100 <> return 101)
37 yieldM $ print (x :: Int)
39 where
41-------------------------------------------------------------------------------
42-- Serial (single-threaded) stream generator loops
43-------------------------------------------------------------------------------
45 -- Generates a value and then loops. Can be used to generate an infinite
46 -- stream. Interleaves the generator and the consumer.
47 loopTail :: Int -> Serial Int
48 loopTail x = do
49 yieldM $ putStrLn "LoopTail..."
50 return x <> (if x < 3 then loopTail (x + 1) else nil)
52 -- Loops and then generates a value. The consumer can run only after the
53 -- loop has finished. An infinite generator will not let the consumer run
54 -- at all.
55 loopHead :: Int -> Serial Int
56 loopHead x = do
57 yieldM $ putStrLn "LoopHead..."
58 (if x < 3 then loopHead (x + 1) else nil) <> return x
60-------------------------------------------------------------------------------
61-- Concurrent (multi-threaded) adaptive demand-based stream generator loops
62-------------------------------------------------------------------------------
64 loopTailA :: Int -> Serial Int
65 loopTailA x = do
66 yieldM $ putStrLn "LoopTailA..."
67 return x `async` (if x < 3 then loopTailA (x + 1) else nil)
69 loopHeadA :: Int -> Serial Int
70 loopHeadA x = do
71 yieldM $ putStrLn "LoopHeadA..."
72 (if x < 3 then loopHeadA (x + 1) else nil) `async` return x
74-------------------------------------------------------------------------------
75-- Parallel (fairly scheduled, multi-threaded) stream generator loops
76-------------------------------------------------------------------------------