2013年11月30日土曜日

開発環境

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

その他参考書籍

9.5(練習問題)、13.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}
import qualified Data.Map as Map
import qualified Data.Char as Char
import System.Environment

main :: IO ()
main = do
    args <- getArgs
    allContents <- mapM readFile args
    let freq = freqMap . countBirds . concat $ allContents
    mapM_ putStr $ map (\k -> show k ++ "\n" ++ 
                              (concat $ map (\x -> ' ':x ++ "\n") $
                                            freq Map.! k)) $
                       Map.keys freq

freqMap :: (Ord a) => Map.Map k a -> Map.Map a [k]
freqMap = Map.fromListWith (++) . map (\(a, b) -> (a, [b])) .
    map swap . Map.toList

swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)

countBirds :: String -> Map.Map String Int
countBirds s = Map.fromListWith (+) $ zip (map trim $ lines s) [1, 1..]

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

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

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

入出力結果(Terminal, runghc)

$ cat bird1.txt
b
c
d
e
f
b
c
d
e
b
c
d
b
c
b
$ cat bird2.txt
a
b
c
d
e
a
b
c
d
a
b
c
a
b
a
$ runghc Sample.hs bird1.txt bird2.txt
1
 f
3
 e
5
 d
 a
7
 c
9
 b
$

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

0 コメント:

コメントを投稿