on fa1318e help sign in
streamly/examples/FileIOExamples.hs
63 lines 2.1 kB history raw
1import qualified Streamly.Prelude as S
2import qualified Streamly.Data.Fold as FL
3import qualified Streamly.Memory.Array as A
4import qualified Streamly.Internal.Prelude as IP
5import qualified Streamly.Internal.FileSystem.File as File
7import Data.Char (ord)
8import System.Environment (getArgs)
10cat :: FilePath -> IO ()
11cat src =
12 File.writeChunks "/dev/stdout"
13 $ File.toChunksWithBufferOf (256*1024) src
15cp :: FilePath -> FilePath -> IO ()
16cp src dst =
17 File.writeChunks dst
18 $ File.toChunksWithBufferOf (256*1024) src
20append :: FilePath -> FilePath -> IO ()
21append src dst =
22 File.appendChunks dst
23 $ File.toChunksWithBufferOf (256*1024) src
25ord' :: Num a => Char -> a
26ord' = (fromIntegral . ord)
28wcl :: FilePath -> IO ()
29wcl src = print =<< (S.length
30 $ S.splitOnSuffix (== ord' '\n') FL.drain
31 $ File.read src)
33grepc :: String -> FilePath -> IO ()
34grepc pat src = print . (subtract 1) =<< (S.length
35 $ IP.splitOnSeq (A.fromList (map ord' pat)) FL.drain
36 $ File.read src)
38avgll :: FilePath -> IO ()
39avgll src = print =<< (S.fold avg
40 $ S.splitOnSuffix (== ord' '\n') FL.length
41 $ File.read src)
42 where avg = (/) <$> toDouble FL.sum <*> toDouble FL.length
43 toDouble = fmap (fromIntegral :: Int -> Double)
45llhisto :: FilePath -> IO ()
46llhisto src = print =<< (S.fold (FL.classify FL.length)
47 $ S.map bucket
48 $ S.splitOnSuffix (== ord' '\n') FL.length
49 $ File.read src)
50 where
51 bucket n = let i = n `div` 10 in if i > 9 then (9,n) else (i,n)
53main :: IO ()
54main = do
55 src <- fmap head getArgs
57 putStrLn "cat" >> cat src -- Unix cat program
58 putStr "wcl " >> wcl src -- Unix wc -l program
59 putStr "grepc " >> grepc "aaaa" src -- Unix grep -c program
60 putStr "avgll " >> avgll src -- get average line length
61 putStr "llhisto " >> llhisto src -- get line length histogram
62 putStr "cp " >> cp src "dst-xyz.txt" -- Unix cp program
63 putStr "append " >> append src "dst-xyz.txt" -- Appending to file