ファイルを行単位で処理する
以下のようなテキストファイルsample.txtがあるとします。
code:_
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
code: (hs)
import System.IO
:t hGetLine
hGetLine :: Handle -> IO String
handle <- openFile "sample.txt" ReadMode
hGetLine handle
"Lorem ipsum dolor sit amet, consectetur"
hGetLine handle
"adipiscing elit, sed do eiusmod tempor"
hGetLine handle
"incididunt ut labore et dolore magna aliqua."
hGetLine handle
*** Exception: sample.txt: hGetLine: end of file
code: (hs)
:{
| countLines :: Handle -> IO ()
| countLines handle = do
| isEOF <- hIsEOF handle
| if isEOF
| then pure ()
| else do
| line <- hGetLine handle
| print (length $ words line)
| countLines handle
| :}
handle <- openFile "sample.txt" ReadMode
countLines handle
6
6
7