ファイル読み込みでのモナドを使っている感じ
do記法でのファイル読み込み
import System.IO printFile :: String -> IO() printFile path = do handle <- openFile path ReadMode contents <- hGetContents handle putStrLn contents hClose handle
型を確認する。
> :t openFile openFile :: FilePath -> IOMode -> IO Handle > :t hGetContents hGetContents :: Handle -> IO String > :t putStrLn putStrLn :: String -> IO ()
IOを揃える。
openFile :: FilePath -> IOMode -> IO Handle hGetContents :: Handle -> IO String putStrLn :: String -> IO ()
上下に重なった部分は IO a -> (IO -> m b)
の構造を持っていることがわかる。IOがベースとなって、Handle
,String
,()
と変化していくことがわかる。
実行結果 (クローズは端折った)
> openFile "test.txt" ReadMode >>= hGetContents >>= putStrLn foo bar