about design, development, profession and avoidance of fluff

Labeling Trees - Exercise 1

Apr 7th, 2013

In the last post of this series we learned how to label a binary tree monadically, and in doing so we discovered the state monad. I’ve collected the pieces we built incrementally last time into this gist containing the whole monadic label implementation as a LINQPad query that you can simply copy and run. I’ll keep making changes to that gist and create links which point to specific revisions from now on.

As I mentioned in the introduction I decided to write this series as a result of watching some years ago Brian Beckman talking about monads and not being able to grasp the topic at that time. Going through it again and explaining what it took me to understand it will hopefully help someone else follow the same path. Up until now we’ve rediscovered what Brian explained in his interviews, but the accompanying source code (that I’ve copied in this gist for convenience) also gave 10 assignments to the reader - without solutions - which I’m going to tackle in the remainder of this series.

The exercises are of varying difficulties, basically expanding on the topic of the state monad with tasks which require generalizing the pattern and applying it to solve problems other than labeling binary trees. So, without further ado, let’s move on to the first exercise.

Exercise 1

generalize over the type of the state, from int
to <TState>, say, so that the S type can handle any kind of
state object. Start with Labeled<T> –> StateContent<TState, T>, from
“label-content pair” to “state-content pair”.

I rephrased the original text of the exercise a little bit so it matches our own implementation rather than Brian’s. Some type names are different as well as some design choices, but the overall concept is the same. Let’s see what this exercise is about.

So far we used a Labeled<T> class to represent the contents of a labeled tree - leaves, specifically. This class is a simple container of label and value pairs, where only the latter is generically parameterized via the T generic parameter. This exercise requires to parameterize the type of the label/state too, which is currently fixed to be an integer. It doesn’t sound very difficult, does it? We simply come up with a new type StateContent<TState, T> which does just that, and then adapt the usages of Labeled<T> to match the new type.

In addition to that we’ll also have to make some changes to the S<T> class, because it’s hardcoding the type of the state to be an integer. This will in turn require some changes to the MLabel1 function, mainly to cope with limited type inference capabilities of the C# compiler. The end result is shown in the diff below.