Created
December 3, 2011 02:21
-
-
Save mmitou/1425782 to your computer and use it in GitHub Desktop.
parserをモナドで書いてみる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Monad | |
data Parser a = Parser (String -> [(a, String)]) | |
pwrap :: a -> Parser a | |
pwrap v = Parser $ \inp -> [(v, inp)] | |
pbind :: Parser a -> (a -> Parser b) -> Parser b | |
pbind (Parser p) f = Parser $ \inp -> case p inp of | |
[] -> [] | |
[(x, s)] -> parse (f x) s | |
string :: String -> Parser String | |
string [] = pwrap [] | |
string (x:xs) = char x `pbind` \v -> | |
string xs `pbind` \vs -> | |
pwrap (v:vs) | |
instance Monad Parser where | |
return v = Parser $ \inp -> [(v, inp)] | |
(>>=) (Parser p) f = Parser $ \inp -> case p inp of | |
[] -> [] | |
[(x,s)] -> parse (f x) s | |
stringm :: String -> Parser String | |
stringm [] = pwrap [] | |
stringm (x:xs) = do v <- char x | |
vs <- stringm xs | |
return (v:vs) | |
------------------------------------------------------------------- | |
parse :: Parser a -> String -> [(a, String)] | |
parse (Parser p) inp = p inp | |
failure :: Parser a | |
failure = Parser $ \inp -> [] | |
item :: Parser Char | |
item = Parser $ \inp -> case inp of | |
[] -> [] | |
(x:xs) -> [(x,xs)] | |
sat :: (Char -> Bool) -> Parser Char | |
sat p = Parser $ \inp -> case (parse item inp) of | |
[] -> [] | |
[(x, s)] -> satisfy | |
where | |
satisfy = if p x | |
then parse (pwrap x) s else [] | |
char :: Char -> Parser Char | |
char x = sat (== x) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment