How can we use our parser combinator function chain to construct more sophisticated parsers?
Well, let’s just try to build a simple parser chain:
chain1 = chain item (\a -> item)
While this will indeed parse the original input sequentially (you can easily verify with parse chain1 “123”), it will throw away the first result, namely a.
Something more must be done: we must explicitly combine the results of both sub-parses. Therefore we need explicit access to the result of the second parse, too. Thus:
chain2 = chain item (\a ->
chain item (\b ->
[The complete code so far can be downloaded here.]
“But where are the Monads?” you may ask. Well, let’s just turn our whole parser into one. Very little code is needed. In fact just:
instance Monad Parser where
return = inject
(>>=) = chain
So, take a deep breath and read on…