Skip to content

Commit db68080

Browse files
committed
add Haskell snippet to read a file in chunks by lines
1 parent f6465f4 commit db68080

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
title: Read File in Chunks
3+
description: Reads a file in chunks grouped by lines.
4+
author: ACR1209
5+
tags: haskell,file,read,chunks,utility
6+
---
7+
8+
```hs
9+
import System.IO (openFile, IOMode(ReadMode), hGetContents)
10+
import Data.List (unfoldr)
11+
12+
readFileInChunks :: FilePath -> Int -> IO [[String]]
13+
readFileInChunks filePath chunkSize = do
14+
handle <- openFile filePath ReadMode
15+
contents <- hGetContents handle
16+
let linesList = lines contents
17+
return $ go linesList
18+
where
19+
go [] = []
20+
go xs = take chunkSize xs : go (drop chunkSize xs)
21+
22+
main :: IO ()
23+
main = do
24+
let file = "example.txt"
25+
let chunkSize = 3 -- Number of lines per chunk
26+
chunks <- readFileInChunks file chunkSize
27+
mapM_ (putStrLn . unlines) chunks
28+
29+
```

0 commit comments

Comments
 (0)