計算機科学のブログ

HaskellのI/O - コマンドラインの操作と遅延I/O - リスト

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT4(HaskellのI/O)、LESSON 22(コマンドラインの操作と遅延I/O)、22.4(練習問題)、Q22-2の解答を求めてみる。

コード

sample.hs

main :: IO ()
main = do
  userInput <- getContents
  mapM_ putStrLn $ selectKakugens $ lines userInput

kakugens :: [String]
kakugens = ["格言1", "格言2", "格言3", "格言4", "格言5"]

selectKakugens :: [String] -> [String]
selectKakugens [] = []
selectKakugens ("n":_) = []
selectKakugens (x:xs) = (kakugens !! (read x - 1)):selectKakugens xs

入出力結果(Terminal, Zsh)

% runghc sample.hs
1
格言1
3
格言3
5
格言5
2
格言2
4
格言4
6
sample.hs: Prelude.!!: index too large
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/List.hs:1368:14 in base:GHC.List
  tooLarge, called at libraries/base/GHC/List.hs:1378:50 in base:GHC.List
  !!, called at sample.hs:12:35 in main:Main
% runghc sample.hs
1
格言1
n
%