on 98259cc help sign in
syntax/Data/Syntax/Combinator.hs
52 lines 1.9 kB history raw
1{- |
2Module : Data.Syntax.Combinator
3Description : Combinators that work with any sequence type.
4Copyright : (c) Daan Leijen 1999-2001, Bryan O'Sullivan 2007-2014, Paweł Nowak 2014
5License : MIT
7Maintainer : Paweł Nowak <pawel834@gmail.com>
8Stability : experimental
10Combinators that work with any sequence type.
11-}
12module Data.Syntax.Combinator where
14import Control.Lens
15import Control.Lens.SemiIso
16import Control.SIArrow
18-- | One or zero occurences of @f@.
19optional :: SIArrow cat => cat () a -> cat () (Maybe a)
20optional f = _Just /$/ f /+/ sipure _Nothing
22-- | Like 'optional', but specialized for @()@.
23opt :: SIArrow cat => cat () () -> cat () ()
24opt f = f /+/ sipure id
26-- | Parser one or zero occurences of @f@, but prints nothing.
27opt_ :: SIArrow cat => cat () () -> cat () ()
28opt_ f = semiIso (const (Left "opt_")) Right /$/ f
29 /+/ sipure id
31-- | @manyTill p end@ applies action p zero or more times until action
32-- end succeeds, and returns the list of values returned by p.
33manyTill :: SIArrow cat => cat () a -> cat () () -> cat () [a]
34manyTill p end = _Empty /$/ end
35 /+/ _Cons /$/ p /*/ manyTill p end
37-- | Zero or more occurences of @v@ separated by @s@.
38sepBy :: SIArrow cat => cat () a -> cat () () -> cat () [a]
39sepBy v s = sepBy1 v s /+/ sipure _Empty
41-- | One or more occurences of @v@ separated by @s@.
42sepBy1 :: SIArrow cat => cat () a -> cat () () -> cat () [a]
43sepBy1 v s = _Cons /$/ v /*/ (s */ sepBy1 v s /+/ sipure _Empty)
45-- | Tries to apply the actions in the list in order, until one of
46-- them succeeds. Returns the value of the succeeding action.
47choice :: SIArrow cat => [cat () a] -> cat () a
48choice = foldr (/+/) (sifail "choice: all alternatives failed")
50-- | Combine two alternatives.
51eitherOf :: SIArrow cat => cat () a -> cat () b -> cat () (Either a b)
52eitherOf a b = _Left /$/ a /+/ _Right /$/ b