You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
instance Monad Parser where<br />
return = unit<br />
(>>=) = bind<br />
Of particular importance is that this particular monad has a zero value (failure), namely the function<br />
which halts reading the stream and returns the empty stream. Together this forms a monoidal structure<br />
with a secondary operation (combine) which applies two parser functions over the same stream and<br />
concatenates the result. Together these give rise to both the Alternative and MonadPlus class instances<br />
which encode the logic for trying multiple parse functions over the same stream and handling failure<br />
and rollover.<br />
e core operator introduced here is the () operator for combining two optional paths of parser logic,<br />
switching to the second path if the first fails with the zero value.<br />
instance MonadPlus Parser where<br />
mzero = failure<br />
mplus = combine<br />
instance Alternative Parser where<br />
empty = mzero<br />
() = option<br />
combine :: Parser a -> Parser a -> Parser a<br />
combine p q = Parser (\s -> parse p s ++ parse q s)<br />
failure :: Parser a<br />
failure = Parser (\cs -> [])<br />
option :: Parser a -> Parser a -> Parser a<br />
option p q = Parser $ \s -><br />
case parse p s of<br />
[] -> parse q s<br />
res -> res<br />
Derived automatically from the Alternative typeclass definition are the many and some functions. Many<br />
takes a single function argument and repeatedly applies it until the function fails and then yields the<br />
collected results up to that point. e some function behaves similar except that it will fail itself if there<br />
is not at least a single match.<br />
-- | One or more.<br />
some :: f a -> f [a]<br />
some v = some_v<br />
where<br />
33