Real World Haskell - 第5章 Part2 The anatomy of a Haskell module 〜 Type inference is a double-edged sword

Real World HaskellHaskell を継続的に勉強中。


Chapter 5. Writing a library: working with JSON data
Chapter 5. Writing a library: working with JSON data

The anatomy of a Haskell module

  • module 宣言を書き、exports を列挙し、where で終わる
    • module 名は大文字で始める
    • module 名とファイル名は同じにするべし
    • JValue(..) のように (..) と書けば、関係する constructor が全てロードされる
    • exports のリストを省略すると、全て export される
module SimpleJSON
    (
      JValue(..)
    , getString
    , getInt
    , getDouble
    , getBool
    , getObject
    , getArray
    , isNull
    ) where

Compiling Haskell source

  • ghc でネイティブコードにコンパイルできる
    • .hi は interface file
    • .o は object file
      • -c option で object code 生成
ghc -c SimpleJSON.hs

Generating a Haskell program, and importing modules

  • executable 作るには Main module と main function 必要
module Main () where

import SimpleJSON

main = print (JObject [("foo", JNumber 1), ("bar", JBool False)])
ghc -o simple Main.hs SimpleJSON.o

Printing JSON data

  • pure なコードと impure なコードをはっきり分ける
renderJValue :: JValue -> String
putJValue :: JValue -> IO ()
putJValue v = putStrLn (renderJValue v)

Type inference is a double-edged sword

  • 型推論は便利だが、明示的に型を書くのは良い習慣である
    • 見つけにくいバグを防げる
    • コードが読み易くなる
  • undefined や error "write me" などを使っているときは特に明示的に型を書くべし