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.