on bac26fc help sign in
streamly/examples/MergeSort.hs
40 lines 1.1 kB history raw
1{-# LANGUAGE FlexibleContexts #-}
3import Data.Word
4import System.Random (getStdGen, randoms)
5import Data.List (sort)
6import Streamly
7import Streamly.Prelude (once)
8import qualified Streamly.Prelude as A
10getSorted :: Stream Word16
11getSorted = do
12 g <- once getStdGen
13 let ls = take 100000 (randoms g) :: [Word16]
14 foldMap return (sort ls)
16-- | merge two streams generating the elements from each in parallel
17mergeAsync :: Ord a => Stream a -> Stream a -> Stream a
18mergeAsync a b = do
19 x <- once $ async a
20 y <- once $ async b
21 merge x y
23merge :: Ord a => Stream a -> Stream a -> Stream a
24merge a b = do
25 a1 <- once $ A.uncons a
26 case a1 of
27 Nothing -> b
28 Just (x, ma) -> do
29 b1 <- once $ A.uncons b
30 case b1 of
31 Nothing -> return x <> ma
32 Just (y, mb) ->
33 if (y < x)
34 then (return y) <> merge (return x <> ma) mb
35 else (return x) <> merge ma (return y <> mb)
37main :: IO ()
38main = do
39 xs <- A.toList $ mergeAsync getSorted getSorted
40 putStrLn $ show $ length xs