ghcでPEGを使おう

30分プログラム、その508。

インストール

Darcsでレポジトリからもってくる。

$ darcs get http://repetae.net/repos/frisby

Cabalを使ってインストール。

$ cd frisby/frisby
$ runghc Setup.lhs configure
$ runghc Setup.lhs build
# runghc Setup.lhs install

ただ、frisby.cabalの依存関係が間違ってるっぽいので、適当に直してやる。

build-depends:       base>=1.0, haskell98>=1.0, mtl>=1.0,containers >= 0.1.0.2,array>=0.1

使ってみる

四則演算のパーサ。おっと、嘘だった。足し算とかけ算のパーサ。

import Text.Parsers.Frisby

data Expr = Expr `Add` Expr | Expr `Mul` Expr | Int Int deriving Show

int = many1 $ oneOf ['0'..'9']
v = int ## (Int . read)
p = v <> many (oneOf "*" ->> v) ## (uncurry $ foldl Mul)
s = p <> many (oneOf "+" ->> p) ## (uncurry $ foldl Add)
e = s

parse = runPeg (newRule e)