Squeezing the F# zipper into a Monad

By: on January 30, 2011

Not being entirely happy with my F# zipper implementation throwing exceptions I decided to investigate whether I could use option types to replace the exceptions thrown when you try to navigate off the tree – for example trying to move up when you are at the top of the tree or move down when you are positioned at a node with no children. The basic implementation is simple enough:

This has the unfortunate side effect of breaking the pipe forward operator:

I could adjust the navigation functions to take an option type as input instead of a plain Location, or I could use a monad to hide the checking of option values. F# has an implementation of monads called computation expressions.

The computation expression required is reasonably simple:

We can now define some composite navigation expressions:

I don’t think that is as pretty as the code with the pipe forward operator so maybe I will bite the bullet and pass option types in and out of the navigation functions! I’ll make the decision once I’ve got slightly more code using my zipper.


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>