2013年11月22日金曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の9章(集合と辞書)、9.5(練習問題)、3.をHaskellで解いてみる。

その他参考書籍

9.5(練習問題)、3.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import Data.List

main :: IO ()
main = do
    contents <- readFile "pdb2lxe.ent.txt"
    print $ authors contents

authors :: String -> [String]
authors = map trim . concat . map splitComma . map (drop $ length "AUTHOR") .
    filter (isPrefixOf "AUTHOR") . lines

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

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

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

splitComma :: String -> [String]
splitComma = fst . foldr  (\x (ys, b) -> if x == ',' then
                                             (ys, False)
                                         else
                                             if b then
                                                 ((x:head ys):tail ys, b)
                                             else
                                                 ([x]:ys, True)) ([], False)

入出力結果(Terminal, runghc)

$ runghc Sample.hs
["P.KRISTIANSEN","M.A.RAHMAN","R.B.AALEN"]
$

{-# OPTIONS -Wall -Werror #-}を記述してるから、細かく型を指定(:: Double)しないと警告がいっぱい出た。慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿