Monadic Parser in JavaScript
Written by on May 14th, 2009 in Uncategorized.

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.
Source: Ajaxian » Front Page
Original Article: http://feedproxy.google.com/~r/ajaxian/~3/e-_S1ecg7Vo/monadic-parser-in-javascript