2013年12月3日火曜日

開発環境

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.8(ファイル形式の設計)、14.10(プログラミング実習)、実習 14-3をHaskellで解いてみる。

その他参考書籍

実習14-3.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import System.Environment

main :: IO ()
main = do
    args <- getArgs
    if length args /= 1 then
        error "Error: Wrong number of arguments\nUsabe is:Sample <filename>"
    else do
        let filename = args !! 0
        contents <- readFile filename
        let (a, b) = triple contents
        writeFile (filename ++ "1.out") (a ++ "\n")
        writeFile (filename ++ "2.out") (b ++ "\n")

triple :: String -> (String, String)
triple s = foldr (\x (a, b) -> if mod (read x :: Int) 3 == 0 then
                                   (x ++ ' ':a, b)
                               else
                                   (a, x ++ ' ':b))
                 ([], []) $ words s

入出力結果(Terminal, runghc)

$ cat numbers
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
-11 -12 -13 -14 -15 -16 -17 -18 -19 -20
$ runghc Sample.hs
Sample.hs: Error: Wrong number of arguments
Usabe is:Sample <filename>
$ runghc Sample.hs numbers
$ cat numbers1.out
3 6 9 12 15 18 -3 -6 -9 -12 -15 -18 
$ cat numbers2.out
1 2 4 5 7 8 10 11 13 14 16 17 19 20 -1 -2 -4 -5 -7 -8 -10 -11 -13 -14 -16 -17 -19 -20 
$

慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿