2013年11月17日日曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の8章(ファイル処理)、8.8(練習問題)、2.をHaskellで解いてみる。

その他参考書籍

8.8(練習問題)、2.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()
main = do
    contents <- readFile "weather.txt"
    let a = lines contents
    mapM_ print $ map string2weather a

type Date = (Int, Int, Int)
type Latitude = (Int, Int, Int)
type Longitude = (Int, Int, Int)
type Data = (Double, Double, Double)

fieldCols :: [[Int]]
fieldCols = [[4, 2, 2], [2, 2, 2], [2, 2, 2], [6, 6, 6]]

dateField :: [Int]
dateField = fieldCols !! 0

latitudeField :: [Int]
latitudeField = fieldCols !! 1

longtitudeField :: [Int]
longtitudeField = fieldCols !! 2

dataField :: [Int]
dataField = fieldCols !! 3

string2weather :: String -> (Date, Latitude, Longitude, Data)
string2weather s =
    let [a, b, c, d] = map sum [dateField, latitudeField, longtitudeField,
                                dataField]
    in (string2Date (take a s),
        string2latitude (take b . drop a $ s),
        string2longtitude (take c . drop (a + b) $ s),
        string2data (take d. drop (sum [a, b, c]) $ s))

string2Date :: String -> Date
string2Date s =
    let [a, b, c] = map (dateField !!) [0..2]
    in (read (take a s) :: Int, read (take b s) :: Int, read (take c s) :: Int)

string2latitude :: String -> Latitude
string2latitude s =
    let [a, b, c] = map (latitudeField !!) [0..2]
    in (read (take a s) :: Int, read (take b s) :: Int, read (take c s) :: Int)

string2longtitude :: String -> Longitude
string2longtitude s =
    let [a, b, c] = map (latitudeField !!) [0..2]
    in (read (take a s) :: Int, read (take b s) :: Int, read (take c s) :: Int)

string2data :: String -> Data
string2data s =
    let [a, b, c] = map (latitudeField !!) [0..2]
    in (read (take a s) :: Double, read (take b s) :: Double,
        read (take c s) :: Double)

入出力結果(Terminal, runghc)

$ runghc Sample.hs
((2007,20,20),(24,24,24),(38,38,38),(10.0,10.0,10.0))
((2007,20,20),(24,24,24),(38,38,38),(10.0,10.0,10.0))
$

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

0 コメント:

コメントを投稿