開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
- The Haskell Platform (インストール方法、モジュール等)
C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の14章(ファイル入出力)、14.1(ファイル関数)、14.2(変換ルーチン)、14.3(バイナリファイルとASCIIファイル)、14.4(行終端にまつわる謎)、14.5(バイナリI/O)、14.6(バッファリングの問題)、14.7(バッファリングを行わないI/O)、設問 14-3をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
設問14-3.
コード(BBEdit)
Sample.hs
{-# OPTIONS -Wall -Werror #-} import System.Environment import System.Directory import System.IO import Control.Exception import qualified Data.ByteString.Lazy as BL main :: IO () main = do args <- getArgs if length args /= 2 then error "Error: Wrong number of arguments\nUsabe is:copy <from> <to>" else copy (args !! 0) (args !! 1) copy :: FilePath -> FilePath -> IO () copy source dest = do contents <- BL.readFile source bracketOnError (openTempFile "." "temp") (\(tempName, tempHandle) -> do hClose tempHandle removeFile tempName) (\(tempName, tempHandle) -> do BL.hPutStr tempHandle contents hClose tempHandle renameFile tempName dest)
入出力結果(Terminal, runghc)
$ ghc --make Sample [1 of 1] Compiling Main ( Sample.hs, Sample.o ) Linking Sample ... $ ./Sample Sample: Error: Wrong number of arguments Usabe is:copy <from> <to> $ ./Sample Sample.hs Sample.hs.bak $ cat Sample.hs.bak {-# OPTIONS -Wall -Werror #-} import System.Environment import System.Directory import System.IO import Control.Exception import qualified Data.ByteString.Lazy as BL main :: IO () main = do args <- getArgs if length args /= 2 then error "Error: Wrong number of arguments\nUsabe is:copy <from> <to>" else copy (args !! 0) (args !! 1) copy :: FilePath -> FilePath -> IO () copy source dest = do contents <- BL.readFile source bracketOnError (openTempFile "." "temp") (\(tempName, tempHandle) -> do hClose tempHandle removeFile tempName) (\(tempName, tempHandle) -> do BL.hPutStr tempHandle contents hClose tempHandle renameFile tempName dest) $ ./Sample abcde abcde.bak Sample: abcde: openBinaryFile: does not exist (No such file or directory) $
{-# OPTIONS -Wall -Werror #-}を記述してるから、細かく型を指定(:: Double)しないと警告がいっぱい出た。慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。
0 コメント:
コメントを投稿