This sucks right now, so don't use it as an example for anything. I'm just trying to figure this stuff out.
Created
July 25, 2010 20:42
-
-
Save jonsterling/489869 to your computer and use it in GitHub Desktop.
A 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
| -- This is a really terrible parser I'm working on to learn Haskell & Parsec. | |
| -- Sorry if it makes your eyes bleed. | |
| module Main where | |
| import Control.Monad(liftM) | |
| import Text.ParserCombinators.Parsec | |
| import Text.ParserCombinators.Parsec.Expr | |
| import qualified Text.ParserCombinators.Parsec.Token as P | |
| import Text.ParserCombinators.Parsec.Language | |
| lexer :: P.TokenParser st | |
| lexer = P.makeTokenParser emptyDef | |
| symbol = P.symbol lexer | |
| parens = P.parens lexer | |
| dot = P.dot lexer | |
| colon = P.colon lexer | |
| data Expr = Var String | |
| | Selector String | |
| | Message (Expr) (Expr) (Expr) | |
| instance Show Expr where | |
| show (Var s) = s | |
| show (Selector x) = "@selector(" ++ x ++ ")" | |
| show (Message x y z) = "objc_msgSend(" ++ (show x) ++ "," ++ (show y) ++ "," ++ (show z) ++ ");" | |
| sentence :: Parser String | |
| sentence = many1 $ noneOf "." | |
| sentences :: Parser [String] | |
| sentences = sentence `sepEndBy` dot | |
| word :: Parser String | |
| word = many1 (letter <|> digit) | |
| message :: Parser Expr | |
| message = | |
| word >>= \r -> space >> | |
| word >>= \s -> colon >> | |
| word >>= \a -> | |
| return $ Message (Var r) (Selector s) (Var a) | |
| readParser :: Parser a -> (a -> String) -> String -> String | |
| readParser parser trans input = | |
| case parse parser "HackTalk" input of | |
| Left err -> "No match: " ++ show err | |
| Right val -> trans val | |
| readSentences :: String -> String | |
| readSentences = readParser sentences $ unlines . map readMessage | |
| readMessage :: String -> String | |
| readMessage = readParser message (id . show) | |
| main = | |
| putStr $ readSentences "dawg bark: loudly. cat meow: likeAKitten. haters gonna: hate." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment