開発環境
- OS X Mavericks - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
- The Haskell Platform (インストール方法、モジュール等)
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の8章(ファイル処理)、8.8(練習問題)、2.をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
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 コメント:
コメントを投稿