Implement a Haskell function using Parsec to parse a recursive arithmetic grammar…
- User
Implement a Haskell function using
Parsecto parse a recursive arithmetic grammar (handling parentheses precedence). Assistant
Implement a Haskell function using Parsec to parse a recursive arithmetic grammar (handling parentheses precedence).
1. Understand the Goal: The user wants a Haskell function using the Parsec library to parse a recursive arithmetic grammar. Specifically, it needs to handle operator precedence and parentheses.
Identify Key Components:
expr ::= term (addop term)*term ::= factor (mulop factor)*factor ::= parens expr | number | variable (maybe just number/parens for simplicity, but the prompt implies "recursive", so parens are crucial).addop ::= + | -mulop ::= * | /Text.Parsec (or Text.Parsec.String usually).Design the AST: What data structure represents arithmetic?
data Expr = Num Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show, Eq)
Self-Correction: Maybe just BinOp Op Expr Expr is cleaner?
data Op = Add | Sub | Mul | Div
data Expr = Const Int | BinOp Op Expr Expr
This is good, but specific constructors are often easier for beginners to read. I'll stick to specific constructors for clarity.
Drafting the Parsers (Mental Draft):
Lexeme wrapper: To handle spaces easily.
lexeme p = do { x <- p; spaces; return x }
symbol s = lexeme (string s)
Number Parser:
number = do
n <- many1 digit
return (Num (read n))
Factor (Atoms + Parens): This is where recursion happens.
factor = try parenExpr <|> number
parenExpr = between (symbol "(") (symbol ")") expr
Term (Mul/Div): Standard "chain" pattern.
term = chainl1 factor mulOp
mulOp = (symbol "*" >> return Mul) <|> (symbol "/" >> return Div)
Expr (Add/Sub): Standard "chain" pattern.
expr = chainl1 term addOp
addOp = (symbol "+" >> return Add) <|> (symbol "-" >> return Sub)
Refining the Implementation:
Text.Parsec, Text.Parsec.String, Control.Applicative (though Parsec is monadic, some operators are handy), Data.Char.parseExpr :: String -> Either ParseError Expr.Step-by-Step Code Construction:
Step 1: Data Types.
data Expr = Val Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show)
Step 2: Basic Parsers.
Define natural (integer) and reservedOp (handling spaces).
Parsec has lexeme in Text.Parsec.Token, but writing a manual one is often more educational for a specific request like this. Let's stick to manual spaces handling to keep dependencies minimal (just parsec).
-- Consume spaces
whiteSpace = spaces
-- Parse a symbol and consume trailing spaces
symbol s = string s <* whiteSpace
Step 3: Number parser.
integer = read <$> many1 digit <* whiteSpace
Step 4: Parentheses & Atoms.
parens = between (symbol "(") (symbol ")")
atom = (Val <$> integer) <|> parens expr -- Recursive call to expr
Step 5: Multiplication/Division (Higher precedence).
Use chainl1. It's the idiomatic Parsec way to handle left-associative operations.
term = chainl1 atom mulOp
mulOp = (symbol "*" *> pure Mul) <|> (symbol "/" *> pure Div)
Step 6: Addition/Subtraction (Lower precedence).
expr = chainl1 term addOp
addOp = (symbol "+" *> pure Add) <|> (symbol "-" *> pure Sub)
Step 7: Putting it together. Wrapper function.
Review and Refine:
1 + 2 * 3? Yes, term binds tighter than expr.(1 + 2) * 3? Yes, parens calls expr, which allows breaking precedence.whiteSpace is consumed after tokens.expr calls term, term calls atom, atom calls parens expr.Final Code Structure:
Expr.expr, term, factor.chainl1 for elegance.main or test block to demonstrate functionality.Alternative Approaches:
One could use buildExpressionParser from Text.Parsec.Expr. This is arguably "better" for complex grammars, but implementing the precedence climbing manually (as done above) is usually preferred when teaching/explaining the grammar structure explicitly. The prompt asks to "implement a function... to parse", implying showing the grammar structure. I will provide the manual chainl1 approach as it maps 1:1 to the standard BNF grammar, making it easier to understand the recursion and precedence. I will mention buildExpressionParser as a side note.
Self-Correction on try: In atom, we have <|>. integer consumes digits. If it sees (, integer fails immediately without consuming input, so try isn't strictly necessary there unless we had a parser that consumed prefix characters before failing. But integer only consumes digits. However, parens starts with (. If we swap them: parens <|> integer, parens consumes (. If the next char is not ), it fails. If it fails, did it consume input? Yes, (. So try is needed if parens is first. Since integer cannot start with (, integer <|> parens is safe without try.
Constructing the Response:
This looks solid. I will write the code now.
Refining the specific imports:
import Text.Parsec
import Text.Parsec.String (Parser)
import Control.Applicative ((<*>), (<$>), (<*), (*>), (<|>))
Wait, modern GHC (base 4.8+) exports Applicative from Prelude, so explicit imports aren't strictly necessary but good for compatibility with older GHCs or strict linting. I'll stick to standard Parsec imports.
Code logic check:
expr = chainl1 term addop
term = chainl1 factor mulop
factor = integer <|> parens expr
This is the classic structure.
Let's write the explanation clearly.
expr -> term -> factor -> parens -> expr.chainl1 enforces that term (multiplication) binds tighter than expr (addition).Okay, ready to generate output.
Here is a complete, self-contained Haskell implementation using Parsec.
It implements a standard recursive descent parser for arithmetic expressions, handling:
1 - 2 - 3 parses as (1 - 2) - 3).module ArithmeticParser (parseExpr, Expr(..)) where
import Text.Parsec
import Text.Parsec.String (Parser)
import Control.Applicative ((<**>))
-- 1. Define the Abstract Syntax Tree (AST)
-- This represents the structure of the code after parsing.
data Expr = Num Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr
| Div Expr Expr
deriving (Show, Eq)
-- 2. Top-level Parser Wrapper
-- This consumes leading/trailing whitespace and ensures we parse the whole input.
parseExpr :: String -> Either ParseError Expr
parseExpr input = parse (contents expr) "<stdin>" input
where
contents p = spaces *> p <* eof
-- 3. The Grammar Implementation
-- We use the 'chainl1' combinator to handle left-associativity and precedence layers.
-- Level 1: Addition and Subtraction (Lowest Precedence)
-- expr ::= term ( ('+' | '-') term )*
expr :: Parser Expr
expr = term `chainl1` addop
-- Level 2: Multiplication and Division (Higher Precedence)
-- term ::= factor ( ('*' | '/') factor )*
term :: Parser Expr
term = factor `chainl1` mulop
-- Level 3: Atomic units (Numbers, Parentheses)
-- factor ::= int | '(' expr ')'
factor :: Parser Expr
factor = try int <|> parens expr
-- 4. Token Parsers & Helpers
-- Parse an integer, ignoring trailing whitespace
int :: Parser Expr
int = do
-- Parse an optional negative sign followed by digits
-- (Note: Standard simple arithmetic usually handles '-' as a binary op,
-- but we can allow negative literals here if desired, or just read digits)
n <- many1 digit
spaces
return . Num $ read n
-- Parse something wrapped in parentheses, ignoring internal/external whitespace
parens :: Parser a -> Parser a
parens p = between (symbol "(") (symbol ")") p
-- Parse a specific string symbol, consuming trailing whitespace
symbol :: String -> Parser String
symbol s = string s <* spaces
-- Define the operators
addop :: Parser (Expr -> Expr -> Expr)
addop = (symbol "+" >> return Add) <|> (symbol "-" >> return Sub)
mulop :: Parser (Expr -> Expr -> Expr)
mulop = (symbol "*" >> return Mul) <|> (symbol "/" >> return Div)
You can save this into a file named ArithmeticParser.hs and load it in GHCi.
ghci ArithmeticParser.hs
Then test it using the parseExpr function:
-- Simple addition
> parseExpr "1 + 2"
Right (Add (Num 1) (Num 2))
-- Precedence: Multiplication happens before addition
-- "1 + 2 * 3" should be 1 + (2 * 3)
> parseExpr "1 + 2 * 3"
Right (Add (Num 1) (Mul (Num 2) (Num 3)))
-- Parentheses override precedence
-- "(1 + 2) * 3" should be (1 + 2) * 3
> parseExpr "(1 + 2) * 3"
Right (Mul (Add (Num 1) (Num 2)) (Num 3))
-- Left Associativity
-- "10 - 2 - 1" should be (10 - 2) - 1
> parseExpr "10 - 2 - 1"
Right (Sub (Sub (Num 10) (Num 2)) (Num 1))
Expr): We define an Algebraic Data Type. Leaf nodes are Num, and branches are binary operations like Add or Mul.expr calls term.term calls factor.factor binds the tightest (parentheses/numbers), followed by term (multiplication), followed by expr (addition).chainl1: This is a powerful Parsec combinator.
term) and a parser for the operator (e.g., addop).a - b - c becomes (a - b) - c, not a - (b - c)).factor contains parens expr. This closes the loop: an expression contains terms, which contain factors, and a factor can contain a parenthesized expression. This allows for arbitrary nesting like ((1+2)).