2014年2月24日月曜日

開発環境

Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の10章(コード事例研究: バイナリデータフォーマットの構文解析)、10.3(「ボイラープレート」コードの除去)、10.9(今後の方向性)の練習問題 1.を解いてみる。

その他参考書籍

練習問題 1.

前回までのコードでは、中間的な値の取り扱いについて、問題があったので、ParseState型の定義を変更。構文解析器が使っている状態の型で必要なのはString型のみなので、Int型を削除。将来、状態で未処理の文字列以外の状態も含めたくなったときの為に、今のところフィールドは1つでもdataで定義。(本節では解析状態に位置(offset)も含めてあるけど、なるべく単純に、理解しやすくする為に、このコードでは削除)

コード(BBEdit, Emacs)

ParseP2.hs

{-# OPTIONS -Wall -Werror #-}
module PGMP2 where

import Data.Char (isSpace, isDigit)
import Data.List (isPrefixOf)
import System.Environment (getArgs)

main :: IO ()
main = do
    (a:_) <- getArgs
    contents <- readFile a
    let g = parseP2 contents
    print g
    putStrLn "データ"
    print $ fmap greyData g

-- プレーンフォーマット
data GreymapP2 = GreymapP2 {greyWith :: Int,
                            greyHeight :: Int,
                            greyMax :: Int,
                            greyData :: [Int]}
                 deriving (Eq)

instance Show GreymapP2 where
    show (GreymapP2 w h m _) = "GreymapP2 " ++ show w ++ "x" ++ show h ++
                               " " ++ show m
-- 解析状態の型、ParseState型を定義
-- stringは未処理の文字列
data ParseState = ParseState {string :: String} deriving (Show)

-- 続くコードをParseState型を使って書き換えていく
parseP2 :: String -> Maybe GreymapP2
parseP2 s =
    matchHeader "P2" s                   >>?
    \s1 -> skipSpace ((), ParseState s1) >>?
    (getNat . snd)                       >>?
    skipSpace                            >>?
    \(width, state1) -> getNat state1    >>?
    skipSpace                            >>?
    \(height, state2) -> getNat state2   >>?
    over                                 >>?
    skipSpace                            >>?
    \(maxGrey, state3) ->
        getInts (width * height) state3  >>?
    \ns -> Just (GreymapP2 width height maxGrey ns)

(>>?) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>? _ = Nothing
Just x >>? f = f x

skipSpace :: (a, ParseState) -> Maybe (a, ParseState)
skipSpace (x, initState) =
    Just (x, ParseState (dropWhile isSpace (string initState)))

over :: (Int, ParseState) -> Maybe (Int, ParseState)
over (n, initState) | n > 255 = Nothing
            | otherwise = Just (n, initState)

matchHeader :: String -> String -> Maybe String
matchHeader prefix str
    | prefix `isPrefixOf` str =
        Just (drop (length prefix) str)
    | otherwise = Nothing

-- nat(natural number)
getNat :: ParseState -> Maybe (Int, ParseState)
getNat initState = let (num, str) = span isDigit (string initState)
                   in if null num 
                   then Nothing
                   else Just (read num :: Int, ParseState str)

getInts :: Int -> ParseState -> Maybe [Int]
getInts n initState = iter n (' ':string initState) []

iter :: Int -> String -> [Int] -> Maybe [Int]
iter n s ns
    | n == 0 && (null s || null (dropWhile isSpace s)) = Just ns
    | n /= 0 && null s = Nothing
    | n /= 0 && (isSpace (head s)) =
        let (num, str) = span isDigit (tail s)
        in if null num
        then Nothing
        else iter (n - 1) str (ns ++ [read num :: Int])
    | otherwise = Nothing

入出力結果(Terminal, runghc)

$ runghc ParseP2.hs test.pgm
Just GreymapP2 24x7 15
データ
Just [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,7,7,7,7,0,0,11,11,11,11,0,0,15,15,15,15,0,0,3,0,0,0,0,0,7,0,0,0,0,0,11,0,0,0,0,0,15,0,0,15,0,0,3,3,3,0,0,0,7,7,7,0,0,0,11,11,11,0,0,0,15,15,15,15,0,0,3,0,0,0,0,0,7,0,0,0,0,0,11,0,0,0,0,0,15,0,0,0,0,0,3,0,0,0,0,0,7,7,7,7,0,0,11,11,11,11,0,0,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
$

次回はパターンマッチで使っているタプル(ペア)、(a, ParseState)を隠す。

0 コメント:

コメントを投稿