Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {- CIS 194 HW 11
- due Monday, 8 April
- -}
- module Week11.SExpr where
- import Week11.AParser
- import Control.Applicative
- import Data.Char(isSpace, isAlpha, isAlphaNum)
- ------------------------------------------------------------
- -- 1. Parsing repetitions
- ------------------------------------------------------------
- zeroOrMore :: Parser a -> Parser [a]
- zeroOrMore p = many_v
- where many_v = some_v <|> pure []
- some_v = (:) <$> p <*> many_v
- oneOrMore :: Parser a -> Parser [a]
- oneOrMore p = some_v
- where many_v = some_v <|> pure []
- some_v = (:) <$> p <*> many_v
- ------------------------------------------------------------
- -- 2. Utilities
- ------------------------------------------------------------
- spaces :: Parser String
- spaces = zeroOrMore (satisfy isSpace)
- ident :: Parser String
- ident = (:) <$> satisfy isAlpha <*> zeroOrMore (satisfy isAlphaNum)
- ------------------------------------------------------------
- -- 3. Parsing S-expressions
- ------------------------------------------------------------
- -- An "identifier" is represented as just a String; however, only
- -- those Strings consisting of a letter followed by any number of
- -- letters and digits are valid identifiers.
- type Ident = String
- -- An "atom" is either an integer value or an identifier.
- data Atom = N Integer | I Ident
- deriving Show
- -- An S-expression is either an atom, or a list of S-expressions.
- data SExpr = A Atom
- | Comb [SExpr]
- deriving Show
- parseAtom :: Parser Atom
- parseAtom = ( N <$> (spaces *> posInt)) <|> ( I <$> (spaces *> ident))
- parseSExpr :: Parser SExpr
- parseSExpr = (A <$> parseAtom) <|> Comb <$> (spaces *> char '(' *> oneOrMore (parseSExpr) <* spaces <* char ')')
Advertisement
Add Comment
Please, Sign In to add comment