2014年2月25日火曜日

開発環境

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

その他参考書籍

練習問題 1.

前回までのコード

コード(BBEdit, Emacs)

ParseP2.hs

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

import Control.Applicative ((<$>))
import Data.Char (isSpace, isDigit)
import System.Environment (getArgs)

main :: IO ()
main = do
    (a:_) <- getArgs
    contents <- readFile a
    let g = parseP2 (ParseState contents)
    print $ fmap fst g
    putStrLn "データ"
    print $ greyData <$> fst <$> 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)

{--
タプル(ペア)のパターンマッチを除去
各解析関数(matchHeader, skipSpaces, parseNat, parseInts)関数を
解析状態を第一引数としてとり、解析結果に使われる中間的なもの
(幅、高さ、最大グレー値等)と解析状態を返す関数に修正
ParseState -> Maybe (a, ParseState)
(aが中間的なもの)
--}
parseP2 :: ParseState -> Maybe (GreymapP2, ParseState)
parseP2 =
    parseHeader ==> \header -> skipSpaces ==>&
    assert (header == "P2")               ==>&
    parseNat ==> \width -> skipSpaces     ==>&
    parseNat ==> \height -> skipSpaces    ==>&
    parseNat ==> \maxGrey -> skipSpaces   ==>&
    assert (maxGrey <= 255)               ==>&
    parseInts (width * height) ==> \ns ->
        \s -> Just (GreymapP2 width height maxGrey ns, s)

(==>) :: (ParseState -> Maybe (a, ParseState)) ->
         (a -> ParseState -> Maybe (b, ParseState)) ->
         ParseState -> Maybe (b, ParseState)
firstParser ==> secondParser = chainedParser
    where chainedParser initState =
              case firstParser initState of
                   Nothing -> Nothing
                   Just (firstResult, newState) ->
                       secondParser firstResult newState

(==>&) :: (ParseState -> Maybe (a, ParseState)) ->
          (ParseState -> Maybe (b, ParseState)) ->
          ParseState -> Maybe (b, ParseState)
p ==>& f = p ==> \_ -> f

skipSpaces :: ParseState -> Maybe ((), ParseState)
skipSpaces initState =
    Just ((), ParseState (dropWhile isSpace (string initState)))

assert :: Bool -> (ParseState -> Maybe ((), ParseState))
assert True  = \s -> Just ((), s)
assert False = \_ -> Nothing

parseHeader :: ParseState -> Maybe (String, ParseState)
parseHeader initState =
    let str = string initState
        header = takeWhile (not . isSpace) str
    in Just (header, ParseState (drop (length header) str))

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

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

iter :: Int -> String -> [Int] -> Maybe ([Int], ParseState)
iter n s ns
    | n == 0 && (null s || null (dropWhile isSpace s))
        = Just (ns, ParseState s)
    | 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]
$ runghc ParseP2.hs ParseP2.hs 
Nothing
データ
Nothing
$ cat test.pgm 
P2
24 7
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 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
$

次回は解析器の型の詳細を隠す。

0 コメント:

コメントを投稿