Haskell: write yourself a Monad in almost no time (2)

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

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Haskell: write yourself a Monad in almost no time (2)

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s