Thursday, May 14th, 2009

Monadic Parser in JavaScript

Category: JavaScript, Utility

Jens Schmidt pointed us to an interesting project by “Mu Dynamics Research Labs” called p4js:

p4js is a monadic parser library that provides the basic monadic operators return and bind

The announcement blog post explains some of the motivations behind the project:

After exploring Haskell for some time, I find myself often adopting functional concepts in my daily work. The exposure to functional programming has even affected the set of tools and frameworks I use. For example, having to parse a custom data format I first tend to search for a Parsec clone implemented in the currently used language. This time it was for JavaScript, but a quick Google search did not reveal any relevant projects. Therefore following is the initial attempt to a probably first general purpose parser library for JavaScript, ‘p4js’.

For the uninitiated to monadic styles and syntax, the introduction blog post has a short tutorial explaining the basics; the key bits to understand are that:

  • The function $P() creates a parser object that can be executed on an input using the parse(input) function
  • Each function on the parser (called combinators) returns an instance of the parser to make invocation chaining easy
  • Once you define an interesting chain, you can register it with the parser for easy reference, as in p.register(’nat’) and use it from now on as $P().nat()

The current library provides only a dozen combinators, but it is enough to have quite some fun already. Following are few examples:

* a CSV parser,
* a small calculator and
* the tiny math processor that uses the parser not only to parse the input into expression tree, but also to perform expression evaluation and function derivation on the tree, and to draw function graphs (on browsers that support the canvas tag).

In the comments of the announcement post, a couple of people also point at Chris Double’s implementation of the same concept.

Posted by Ben Galbraith at 10:32 am
3 Comments

+++--
3.9 rating from 27 votes

3 Comments »

Comments feed TrackBack URI

Cool. Is anybody going to write an applicative one? :)

Thanks for pointing to Chris’ library, too.

BTW, don’t be confused with the word “monad”, it’s nothing special. To get to know it, you’ll have to read up on functors, pointed functors, applicative functors first. (Yes, I know it sounds like hell. :))

Comment by chiaroscuro — May 14, 2009

off topic, but what’s happening with the news flow on ajaxian? i got used to 4-5 posts a day, and now we have only one or two of them..

Comment by mare — May 15, 2009

is there something wrong with the tag display?
–> Category: JavaScriptView the technorati tag: JavaScript, UtilityView the technorati tag: Utility

Comment by Novalis — May 15, 2009

Leave a comment

You must be logged in to post a comment.