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