A parser combinator library provides reusable first-class functions for composing small parsers into larger monadic parsers. In Haskell, this supports practical parsing while handling effects, errors, and failures cleanly. section 12.0 section 12.2
Common combinators support recurring parser structures:
- between applies parsers around a beginning, middle, and end, such as parsing an integer between parentheses. section 12.2
- skipMany repeats a parser zero or more times, such as skipping spaces before and after an integer. section 12.2
- choice, takeWhile, and monadic bind compose alternatives, repeated input conditions, and sequential parsing actions. section 12.2
The parser-combinators library supplies useful combinators for building parsers. Related Haskell libraries serve different needs: Megaparsec emphasizes broad functionality and detailed errors, while Attoparsec specializes in performant raw-byte parsing and incremental input. section 12.2
Parsing a parenthesized integer
Define parenInteger with between (string "(") (string ")") integer. Running it on "(123)" returns 123; running it on "(123" reports a failed closing-parenthesis parse. section 12.2
ghci> import Control.Monad.Combinators
ghci> parenInteger = between (string "(") (string ")") integer
ghci> runParser parenInteger "(123)"
("",Right 123)
ghci> runParser parenInteger "(123"
("",Left "failed to parse \")\"")
ghci> skipSpaces = skipMany $ string " "
ghci> integerWithSpaces = between skipSpaces skipSpaces integer
ghci> runParser integerWithSpaces " 123 "
("",Right 123)
Explore executable GHCi examples for parenthesized integers, whitespace handling, successful results, and parse failures. section 12.2
