If you came here without having read part1 you may wish to do so now.

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 ->

inject [a,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…

Pingback: Haskell: write yourself a Monad in almost no time | Codingcactus's Blog

Pingback: Haskell: write yourself a Monad in almost no time (3) | Codingcactus's Blog