計算機科学のブログ

HaskellのI/O - ファイル操作 - ファイルを開いて閉じる - hIsEOF関数, hGetLine関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT4(HaskellのI/O)、LESSON 24(ファイル操作)、24.1(ファイルを開いて閉じる)、クイックチェック 24-2の解答を求めてみる。

コード

sample2.hs

import System.IO
main :: IO ()
main = do
  file <- openFile "temp.txt" ReadMode
  hasLine <- hIsEOF file
  print hasLine
  firstLine <- if not hasLine
    then hGetLine file
    else return ""
  putStrLn $ mconcat ["first line: ", firstLine]
  hasLine <- hIsEOF file
  print hasLine
  secondLine <- if not hasLine
    then hGetLine file
    else return ""
  putStrLn $ mconcat ["second line: ", secondLine]

入出力結果(Terminal, Zsh)

% runghc sample2.hs
False
first line: line1
True
second line: 
%