Safe Haskell | Safe-Inferred |
---|---|
Language | Haskell2010 |
Efficient literal branching using Template Haskell.
Documentation
switch :: Q Exp -> Q Exp Source #
This is a template function which makes it possible to branch on a collection of string literals in
an efficient way. By using switch
, such branching is compiled to a trie of primitive parsing
operations, which has optimized control flow, vectorized reads and grouped checking for needed input
bytes.
The syntax is slightly magical, it overloads the usual case
expression. An example:
$(switch [| case _ of "foo" -> pure True "bar" -> pure False |])
The underscore is mandatory in case _ of
. Each branch must be a string literal, but optionally
we may have a default case, like in
$(switch [| case _ of "foo" -> pure 10 "bar" -> pure 20 _ -> pure 30 |])
All case right hand sides must be parsers with the same type. That type is also the type
of the whole switch
expression.
A switch
has longest match semantics, and the order of cases does not matter, except for
the default case, which may only appear as the last case.
If a switch
does not have a default case, and no case matches the input, then it returns with
failure, without having consumed any input. A fallthrough to the default case also does not
consume any input.
switchWithPost :: Maybe (Q Exp) -> Q Exp -> Q Exp Source #
Switch expression with an optional first argument for performing a post-processing action after
every successful branch matching, not including the default branch. For example, if we have
ws :: ParserT st e ()
for a whitespace parser, we might want to consume whitespace after matching
on any of the switch cases. For that case, we can define a "lexeme" version of switch
as
follows.
switch' :: Q Exp -> Q Exp switch' = switchWithPost (Just [| ws |])
Note that this switch'
function cannot be used in the same module it's defined in, because of the
stage restriction of Template Haskell.