technology from back to front

Squeezing the F# zipper into a Monad

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.

Tags:

by
tim
on
30/01/11
 
 
2000-13 LShift Ltd, 1st Floor Office, Hoxton Point, 6 Rufus Street, London, N1 6PE, UK +44 (0)20 7729 7060