2013年12月22日日曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の12章(各種ツール)、12.7(練習問題)、12-18.をHaskellで解いてみる。

その他参考書籍

12.7(練習問題)、12-18.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import System.Environment
import System.IO
import Data.Char

main :: IO ()
main = do
    (a:_) <- getArgs
    processFile a

processFile :: String -> IO ()
processFile filename = do
    withFile filename ReadMode $ \handle -> do
        contents <- hGetContents handle
        mapM_ putStrLn $ map trim (lines contents)

trim :: String -> String
trim = ltrim . rtrim

ltrim :: String -> String
ltrim s = drop (length $ takeWhile isSpace s) s

rtrim :: String -> String
rtrim = reverse . ltrim . reverse

入出力結果(Terminal, runghc)

$ runghc Sample.hs Sample.hs
{-# OPTIONS -Wall -Werror #-}
import System.Environment
import System.IO
import Data.Char

main :: IO ()
main = do
(a:_) <- getArgs
processFile a

processFile :: String -> IO ()
processFile filename = do
withFile filename ReadMode $ \handle -> do
contents <- hGetContents handle
mapM_ putStrLn $ map trim (lines contents)

trim :: String -> String
trim = ltrim . rtrim

ltrim :: String -> String
ltrim s = drop (length $ takeWhile isSpace s) s

rtrim :: String -> String
rtrim = reverse . ltrim . reverse
$

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

0 コメント:

コメントを投稿