Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created December 3, 2011 02:21
Show Gist options
  • Save mmitou/1425782 to your computer and use it in GitHub Desktop.
Save mmitou/1425782 to your computer and use it in GitHub Desktop.
parserをモナドで書いてみる
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