Community
Modules 25

Text.Parsec.Expr

provisional

A helper module to parse "expressions". Builds a parser given a table of operators and associativities.

data Operator s u m a

This data type specifies operators that work on values of type a. An operator is either binary infix or unary prefix or postfix. A binary operator has also an associated associativity.

Infix :: (ParsecT s u m (a -> a -> a)) -> Assoc -> Operator s u m a

Prefix :: (ParsecT s u m (a -> a)) -> Operator s u m a

Postfix :: (ParsecT s u m (a -> a)) -> Operator s u m a

type OperatorTable s u m a = [[Operator s u m a]]

An OperatorTable s u m a is a list of Operator s u m a lists. The list is ordered in descending precedence. All operators in one list have the same precedence (but may have a different associativity).

buildExpressionParser :: (Stream s m t) => OperatorTable s u m a -> ParsecT s u m a -> ParsecT s u m a

buildExpressionParser table term builds an expression parser for terms term with operators from table, taking the associativity and precedence specified in table into account. Prefix and postfix operators of the same precedence can only occur once (i.e. --2 is not allowed if - is prefix negate). Prefix and postfix operators of the same precedence associate to the left (i.e. if ++ is postfix increment, than -2++ equals -1, not -3).

The buildExpressionParser takes care of all the complexity involved in building expression parser. Here is an example of an expression parser that handles prefix signs, postfix increment and basic arithmetic.

 expr    = buildExpressionParser table term
         <?> "expression"

 term    =  parens expr
         <|> natural
         <?> "simple expression"

 table   = [ [prefix "-" negate, prefix "+" id ]
           , [postfix "++" (+1)]
           , [binary "*" (*) AssocLeft, binary "/" (div) AssocLeft ]
           , [binary "+" (+) AssocLeft, binary "-" (-)   AssocLeft ]
           ]

 binary  name fun assoc = Infix (do{ reservedOp name; return fun }) assoc
 prefix  name fun       = Prefix (do{ reservedOp name; return fun })
 postfix name fun       = Postfix (do{ reservedOp name; return fun })

Instances

2
  • instance Typeable Assoc
  • instance (Typeable s, Typeable u, Typeable m, Typeable a) => Typeable (Operator s u m a)
Maintainer
derek.a.elkins@gmail.com
Portability
non-portable
Copyright
(c) Daan Leijen 1999-2001, (c) Paolo Martini 2007
License
BSD-style (see the LICENSE file)
Build record and source files

Community contribution. The service has not verified this documentation. The generator reported 3 diagnostics.

Target: Linux on x86-64. Some inferred types and resolved links are not available.

Generator: aihc-haddock-858b1951-web-1

Metadata snapshot: 51a8c38adf37e9558e7835b04b20868626c044e2d2e98e3527943eabd1e09c0a

Open the dependency plan · Download the documentation model

Import a package

Enter a package name and an exact version from Hackage. The site contains imported versions only.