Guest User

Untitled

a guest
Oct 26th, 2011
704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Text.ParserCombinators.Parsec
  2.  
  3. data IntExp = Const Int
  4.             | Add IntExp IntExp
  5.             | Sub IntExp IntExp
  6.  
  7. instance Show (IntExp) where
  8.   show (Const n) = show n
  9.   show (Add l r) = "(" ++ show l ++ "+" ++ show r ++ ")"
  10.   show (Sub l r) = "(" ++ show l ++ "-" ++ show r ++ ")"
  11.  
  12. run :: Show a => Parser a -> String -> IO ()
  13. run p input =
  14.   case parse p "" input of
  15.     Left err ->
  16.       do putStr "parse error at "
  17.          print err
  18.     Right x -> print x
  19.  
  20. parseIntExp :: Parser IntExp
  21. parseIntExp =
  22.   chainl1 parseConstant parseOperation
  23.  
  24. parseOperation :: Parser (IntExp -> IntExp -> IntExp)
  25. parseOperation =
  26.   do spaces
  27.      symbol <- char '+' <|> char '-'
  28.      spaces
  29.      case symbol of
  30.        '+' -> return Add
  31.        '-' -> return Sub
  32.  
  33. parseConstant :: Parser IntExp
  34. parseConstant =
  35.   do xs <- many1 digit
  36.      return $ Const (read xs :: Int)
  37.  
Advertisement
Add Comment
Please, Sign In to add comment