すごいHaskell9章

9.5正誤表もどき

  • 194ページのremove関数が、コマンドライン引数を利用せずハードコーディングされたファイルを使っている。
ページ・行 解説
194ページ・remove関数内19行目 removeFile "todo.txt" removeFile fileName 引数を使うよう修正
194ページ・remove関数内20行目 removeFile tempName "todo.txt" removeFile tempName fileName 同上
  • 同 remove 関数の動作が、196ページの実行例と違う。(削除前のTODOリストが表示される)

5〜8行目を削除する。

Control.Exception を import する。

  • 198p21行め誤字

形クラス→型クラス

9.5 bump 関数の実装

 remove をちょっと変えるだけ。削除の後に、リストの先頭にタスクを追加する。

bump :: [String] -> IO ()
bump [fileName, numberString] = do
    contents <- readFile fileName
    let todoTasks = lines contents
    let numberTask = todoTasks !! (read numberString) #ここを変えた
        newTodoItems = unlines $ numberTask : (delete numberTask  todoTasks) #ここも
    bracketOnError (openTempFile "." "temp")
        (\(tempName, tempHandle) -> do
            hClose tempHandle
            removeFile tempName)
        (\(tempName, tempHandle) -> do
            hPutStr tempHandle newTodoItems
            hClose tempHandle
            removeFile fileName
            renameFile tempName fileName)
bump _ = putStrLn "The bump command takes exactly two argumants"

do ブロックでのコマンドライン引数のパターンマッチ

197pのやつ。引数なしで todo プログラムを起動するとクラッシュするのを防ぐ。

main :: IO ()
main = do
    args <- getArgs
    case args of command:argList -> dispatch command argList
                 _               -> putStrLn "OMG"

ちゃんと動いてるけど、これでいいのかな?

bytestring

 高速化したい時に List やファイル関係の関数の代わりに使うらしい。

head:rest と [first, secand] の違い

 パターンマッチで [first, second] みたいな書き方が出てきて、 head:rest との違いが分からなかったのでメモ。
head はリストの先頭「要素」、rest は残りの「リスト」。first と second はどちらもリストの「要素」。あと、[first, second] リストの要素は first と second だけ。