Friday, December 2, 2011

Better Monad Parse Updated!

I've made a few patches to better-monad-parse and pushed the new version to github. The improvements primarily deal with performance of parsers which parse strings, which I've found is the most common use cases.

This seems to make a big usability improvement for me.

I also improved the =number parser, which had some unexpected behavior.

Better-monad-parse is a monadic parser combinator implementation in pure Elisp which is both useful for writing parsers and understanding how monadic computations work.

Suppose you have a set of files which have names consisting of one or more characters and then a number, which you'd like to write a function to parse. You can do so like:

(require 'better-monad-parse)

(defparser =file-name-parser
 (name <- (=>one-or-more =alpha))
 (number <- =number)
 (m-return 
  `((name . ,name)
    (number . ,number))))

This binds the symbol =file-name-parser to a function which takes a string as input and returns an association list (and the leftover input) as a result, but only if parsing succeeds. Otherwise, it returns nil.

The library provides a rich set of parsers and combinators on parsers (like (=>one-or-more ...) above, which takes a parser and returns a parser which parses at least one, and potentially as many as possible, of the specified parser.

Parsers are generic over the input type, and the library knows how to parse strings, lists and emacs buffers by default. Using my implementation of multimethods, you can extend the parser for other input types.

Using better-monad-parse is kind of like the opposite of slumming - you can go visit the neighborhood of pure, functional, monadic programming from the slums of Emacs Lisp!

0 comments: