Thursday, January 20, 2011

Monads in C#-6. Introducing a simple parser

This is the sixth part of my Monad series. See the introduction for a list of all the posts.

You can find the code for this post on GitHub here.

So far we’ve learnt how to create a simple Monad, the Maybe Monad, and seen how it can help us eliminate boiler plate code by wrapping the mechanics of handling nullability in the Bind function. But as I said before, there’s no real limit to the complexity we can encapsulate in Bind and still treat our Monad as if it were a simple type. To illustrate this, I’m going to leap ahead in complexity and use the canonical Monad example, a Parser Monad. In this post I’ll introduce a simple concept of a Parser and in later posts I’ll show how we can turn it into a Monad.

I’ve ripped this example straight from Graham Hutton’s excellent Haskell textbook, Programming in Haskell.

OK, so let’s think about what a parser does. It takes some input, usually some text, and produces some desired output from it. So a CSV parser would take a text file and output rows and columns of data, preferably typed as numbers, strings and dates. In abstract terms we can think of a parser as a function that takes a string and returns some type T:

Func<string, T>

It’s always easier if we can break large tasks into smaller ones, so it would be good if we could build our parser from lots of mini-parsers. Each mini-parser might only consume some characters of the string, so we really want a function that consumes a string and returns a T and and the unparsed remainder of the input string:

Func<string, Tuple<T,string>>

I’m using the new Tuple type from .NET4 here, but you could just as well NameValuePair or your own custom type.

Our parser might not get a string it understands, so we should be able to account for failure. We’ll do the simplest thing possible for now and reuse our Maybe type:

Func<string, Maybe<Tuple<T,string>>>

Now let’s create a simple parser that just consumes a particular sequence of characters, ‘Hello’:

public static Maybe<Tuple<string, string>> FindHello(string input)
{
return input.StartsWith("Hello")
? new Just<Tuple<string, string>>(Tuple.Create("Hello", input.Skip("Hello".Length).AsString()))
: (Maybe<Tuple<string, string>>)new Nothing<Tuple<string, string>>();
}

If we feed it ‘Hello’ it will return ‘Hello’ plus the remainder of the string:
var result = Parsers.FindHello("Hello World");
var justResult = result as Just<Tuple<string,string>>;
Console.Out.WriteLine("justResult.Value.Item1 = {0}", justResult.Value.Item1);
// justResult.Value.Item1 = Hello
Console.Out.WriteLine("justResult.Value.Item2 = {0}", justResult.Value.Item2);
//justResult.Value.Item2 = World

If we feed it ‘Goodbye’ it will return Nothing:
var result2 = Parsers.FindHello("Goodbye World");
Console.Out.WriteLine("result2 = {0}", result2);
// result2 = Nothing
 
We can make our parser a little more generic by creating a little parser factory that can make a token parser for any sequence of characters. But first, to make our lives easier, let’s define a Parser delegate:
public delegate Maybe<Tuple<T, string>> Parser<T>(string input);

Now here’s our ‘Find’ generator, we’ll write it as an extension method:
public static Parser<string> Find(this string stringToFind)
{
return s => s.StartsWith(stringToFind)
? new Just<Tuple<string, string>>(Tuple.Create(stringToFind,s.Skip(stringToFind.Length).AsString()))
: (Maybe<Tuple<string, string>>)new Nothing<Tuple<string, string>>();
}

This is a higher order function, it returns a function, our parser. Don’t loose sight of the fact that Parser<T> represents a delegate.
 
Now we can use it to make a couple of parsers, a ‘Hello’ parser and a ‘World’ parser:
var helloParser = "Hello".Find();
var worldParser = "World".Find();

Let’s write a convenience extension method to turn parse results into strings:
 
public static string AsString<T>(this Maybe<Tuple<T,string>> parseResult, Func<T, string> unwrap)
{
var justParseResult = parseResult as Just<Tuple<T, string>>;

return (justParseResult != null)
? unwrap(justParseResult.Value.Item1)
: "Nothing";
}

Now we can use our helloParser and worldParser to parse strings:
var result = helloParser("Hello World").AsString(s => s);
Console.Out.WriteLine("result = {0}", result);
// result = Hello

var result2 = worldParser("World Hello").AsString(s => s);
Console.Out.WriteLine("result2 = {0}", result2);
// result2 = World

How could we join them together to make a parser for ‘HelloWorld’ (we won’t worry about whitespace just yet). Here’s a brute force attempt:
Parser<Tuple<string,string>> helloWorldParser = s =>
{
var helloResult = helloParser(s) as Just<Tuple<string, string>>;
if (helloResult == null) return new Nothing<Tuple<Tuple<string, string>, string>>();

var worldResult = worldParser(helloResult.Value.Item2) as Just<Tuple<string, string>>;
if (worldResult == null) return new Nothing<Tuple<Tuple<string, string>, string>>();

return new Just<Tuple<Tuple<string, string>, string>>(Tuple.Create(
Tuple.Create(helloResult.Value.Item1, worldResult.Value.Item1), worldResult.Value.Item2));
};

var result3 = helloWorldParser("HelloWorld").AsString(s => s.Item1 + " " + s.Item2);
Console.Out.WriteLine("result3 = {0}", result3);
// result3 = Hello World

Phew! that was hard work. Imagine if we were combining parsers for anything a little more complex, like our CSV parser for example. We’d have a nasty headache pretty quickly. But don’t worry, we’ll see in the next post that we can turn our parser into a Monad and combine them with sublime simplicity. Stay tuned combinator fans!

Sunday, January 16, 2011

Monads in C#-5. Maybe ;)

This is the fifth part of my Monad series. See the introduction for a list of all the posts.

You can find the code for this post on GitHub here.

In part 3 we created our first Monad, Identity<T>. It was worth starting with the simplest possible thing, so that we could focus on the Monad pattern without being distracted by detail. But working with a useless Monad might well have left you scratching your head, still wondering what the point was. So let’s create our first useful Monad, the Maybe Monad.

We’re used to the idea of nullability in C#. Technically null is a value that any reference type variable can have when it’s not pointing to an actual instance of that type. Nulls are problematic, in fact some people thing they are a mistake. They can be both a bug when we’ve forgotten to initialise a variable, and intentional when we use them to represent some state. Nulls are often used as one of the possible return values from a method when, for some reason, an instance can not be returned.

If I have methods that might return null, I should check the return value for null and execute some alternative branch. If we’ve got a whole chain of methods, any of which might return null, our intention can soon be obfuscated by all the null checks. It would be nice if we could factor these out.

So we want to do two things; first, make the fact that our method might return ‘null’ explicit, and second, factor out the null checks. The Maybe Monad lets us do both. C# has a type Nullable<T>, but it can only be used with value types, so it’s not really what we’re after. Here’s a type called ‘Maybe’, that can or cannot have a value, and its two subtypes, Nothing, which has no value, and Just, which has a value:

public interface Maybe<T>{}

public class Nothing<T> : Maybe<T>
{
public override string ToString()
{
return "Nothing";
}
}

public class Just<T> : Maybe<T>
{
public T Value { get; private set; }
public Just(T value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}

The ToString overrides are not required, they’re just to make the output I write later a little easier. You can just as well write Maybe as a single type with a ‘HasValue’ boolean property, but I quite like this style, it feels closer to the Haskell Maybe.

To make Maybe<T> into a Monad we have to write ToMaybe and Bind methods for it. ToMaybe is simple, we just create a new ‘Just’ from our value:

public static Maybe<T> ToMaybe<T>(this T value)
{
return new Just<T>(value);
}

Bind is more interesting. Remember, Bind is where we put our Monad’s behaviour. We want to factor null checks out of our code, so we need to write Bind so that if the initial value, a, is Nothing, we simply return a Nothing, and only if it has a value do we evaluate the second function:

public static Maybe<B> Bind<A, B>(this Maybe<A> a, Func<A, Maybe<B>> func)
{
var justa = a as Just<A>;
return justa == null ?
new Nothing<B>() :
func(justa.Value);
}

So the Maybe Bind acts a short circuit. In any chain of operations, if any one of them returns Nothing, the evaluation will cease and Nothing will be returned from the entire chain.

Lastly let’s implement SelectMany so that we can use linq syntax to help us out. This time we’ll implement SelectMany in terms of Bind:

public static Maybe<C> SelectMany<A, B, C>(this Maybe<A> a, Func<A, Maybe<B>> func, Func<A, B, C> select)
{
return a.Bind( aval =>
func(aval).Bind( bval =>
select(aval, bval).ToMaybe()));
}

Remember this, we can the same pattern for the SelectMany of any Monad once we have a Bind implementation.

Now let’s do some sums. Here’s a safe division method, its signature explicitly tells us that it might not return an int:

public static Maybe<int> Div(this int numerator, int denominator)
{
return denominator == 0
? (Maybe<int>)new Nothing<int>()
: new Just<int>(numerator/denominator);
}

Now lets chain some division operations together:

public Maybe<int> DoSomeDivision(int denominator)
{
return from a in 12.Div(denominator)
from b in a.Div(2)
select b;
}
 
Look at that, no null checks anywhere to be seen, we’ve successfully factored them out. Now let’s use our DoSomeDivision method with some other types:
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(2)
from c in (new DateTime(2010, 1, 14)).ToMaybe()
select a + " " + b.ToString() + " " + c.ToShortDateString();

Console.WriteLine(result);

Still no null checks and we’re mixing ints, strings and DateTimes. If I run this, it will output:

Hello World! 3 14/01/2010
 
Now if we change the denominator to zero like this:
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(0)
from c in (new DateTime(2010, 1, 14)).ToMaybe()
select a + " " + b.ToString() + " " + c.ToShortDateString();

Console.WriteLine(result);

It outputs:
Nothing

See how the divide by zero Nothing from inside ‘DoSomeDivision’ cascaded up the stack, short circuiting all the other operations on the way? It left us with a Nothing result at the end of the chain. That would have been a pain to write imperatively. Maybe is probably the simplest Monad that is actually useful, but we can already see how it can remove a significant amount of boiler plate.
 
Next we’re going to leap ahead in sophistication and build a parser monad. The insane power we now have will soon become apparent… Mwuhahaha!

Thursday, January 13, 2011

Monads in C#-4. Linq loves Monads!

This is the fourth part of my Monad series. See the introduction for a list of all the posts.

You can find the code for this post on GitHub here.

In part 3 we met our first Monad, Identity<T>. We learnt that for something to become a Monad it had to have a type constructor (Identity<T>), and two methods, ‘Bind’ and ‘ToIdentity’.

// a function 'Bind', that allows us to compose Identity returning functions
public static Identity<B> Bind<A, B>(this Identity<A> a, Func<A, Identity<B>> func)
{
return func(a.Value);
}

public static Identity<T> ToIdentity<T>(this T value)
{
return new Identity<T>(value);
}

I also mentioned that in C# Bind has a different name, SelectMany. It’s one of the extension methods defined for IEnumerable<T>. And as you might have guessed, IEnumerable<T> is in fact a Monad. It’s the Monad poster child for C# in fact :)

So today let’s see how we can implement SelectMany for Identity<T> and free ourselves from the lambda soup we were drowning in in the last post.

Linq takes an interesting approach to Monads, it asks us to write a method that combines Bind and ToXxxx into a single method, SelectMany. SelectMany must have the following signature:

Identity<C> SelectMany<A, B, C>(this Identity<A> a, Func<A, Identity<B>> func, Func<A, B, C> select)

As you can see it looks just like Bind, except it has a third parameter, a function that takes an A and a B and returns a C. It also has a different return type, an Identity<C> instead of an Identity<B>. If your amplified type implements this method, the linq syntax ‘pre-compiler’ (not really, but it’s a good way of thinking about it) can re-write ‘for x in y’ expressions in terms of select many.

Let’s implement SelectMany as an extension method:

public static Identity<C> SelectMany<A, B, C>(this Identity<A> a, Func<A, Identity<B>> func, Func<A, B, C> select)
{
return ???
}

Now we’ll ‘follow the types’ to work out how to write the implementation. First we know we need to return an Identity<C>. The only place we get a C from is the return value of the select function. We can change a C into an Identity<C> by using ToIdentity:

public static Identity<C> SelectMany<A, B, C>(this Identity<A> a, Func<A, Identity<B>> func, Func<A, B, C> select)
{
return select( ??? ).ToIdentity();
}

What do we pass into select? Its first parameter is an A, we can get an A from our ‘a’ parameter by invoking its ‘Value’ method. The second parameter is a B. We can get a B from our previously defined Bind method and then invoke ‘Value’ on that as well:

public static Identity<C> SelectMany<A, B, C>(this Identity<A> a, Func<A, Identity<B>> func, Func<A, B, C> select)
{
return select(a.Value, a.Bind(func).Value).ToIdentity();
}

Let’s expand out Bind because it’s not greatly helping us here:

public static Identity<C> SelectMany<A, B, C>(this Identity<A> a, Func<A, Identity<B>> func, Func<A, B, C> select)
{
return select(a.Value, func(a.Value).Value).ToIdentity();
}

And viola, we have implemented SelectMany for Identity<T>.

Now remember our lambda soup example from the last post? Here it is again:

var result = 
"Hello World!".ToIdentity().Bind( a =>
7.ToIdentity().Bind( b =>
(new DateTime(2010, 1, 11)).ToIdentity().Bind( c =>
(a + ", " + b.ToString() + ", " + c.ToShortDateString())
.ToIdentity())));

Console.WriteLine(result.Value);

We can now rewrite it using Linq syntax like this:

var result =
from a in "Hello World!".ToIdentity()
from b in 7.ToIdentity()
from c in (new DateTime(2010, 1, 11)).ToIdentity()
select a + ", " + b.ToString() + ", " + c.ToShortDateString();

Console.WriteLine(result.Value);

Is that not much nicer? With our new insight into Linq and Monads, we can stop thinking of ‘from x in y’ as a weird attempt to write SQL in C#, but instead see it for what it really is, a kind of Monadic assignment where we assign an unamplified type on the left from an amplified type on the right.

It’s a common misconception that you can only use Linq syntax with IEnumerable<T>, this is incorrect. You can use it for Whatever<T> so long as you implement SelectMany. If you want to use other bits of linq syntax (where, let, join etc) you have to implement the appropriate matching methods, but they can all be constructed from Bind, as we’ll see a little while later.

In the next post we’ll meet our first useful Monad - The Maybe Monad.

Tuesday, January 11, 2011

Monads in C#-3. Creating our first Monad

This is the third part of my Monad series. See the introduction for a list of all the posts.

You can find the code for this post on GitHub here. This post is an almost direct rip-off of Wes Dyer’s excellent post on Monads from 2008.

In the last post I showed how we can do lots of useful things with ‘amplified’ types, like IEnumerable<T>. If we can find a way of composing functions of amplified types we’ll be able to simply write some very powerful programs. We talk a lot about ‘function composition’ when discussing Monads. It can sound very dry and academic, so let’s be clear, function composition is simply programming. When I write some lines of code like this:

var customer = customerData.GetById(customerId);
var order = customer.CreateOrder();

I am doing function composition. In this case composing the ‘GetById’ function with the ‘CreateOrder’ function. Implicitly or explicitly, all programming is function composition.

As programmers we know how to compose functions that consume and return unamplified types, it’s second nature.

Here are two simple functions. They both have the same function type, they both take a single int value argument and return an int. I’m going to use function delegates and lambda expressions rather than writing out static methods, but it’s exactly the same principle:

Func<int, int> add2 = x => x + 2;
Func<int, int> mult2 = x => x*2;

It’s simple to compose these functions:

Func<int, int> add2Mult2 = x => mult2(add2(x));

We can use our new function:

var r2 = add2Mult2(5);
Console.Out.WriteLine("r2 = {0}", r2);

Which prints:
 
r2 = 14

We do this kind of thing all the time. But what if we want to compose functions that return amplified types? First we’ll need an amplified type to compose. For this example, we choose the simplest one possible, it simply wraps a value without adding anything, that will come later. Let’s call it Identity:

public class Identity<T>
{
public T Value { get; private set; }

public Identity(T value)
{
Value = value;
}
}

Now let’s create two functions that return amplified types:

Func<int, Identity<int>> add2 = x => new Identity<int>(x + 2);
Func<int, Identity<int>> mult2 = x => new Identity<int>(x * 2);

If we try to compose these in the same way we composed our simple Func<int, int>s above it won’t compile:

// we can't compose them directly, the types don't match. This won't compile:
Func<int, Identity<int>> add2Mult2 = x => mult2(add2(x));

Because add2 returns an Identity<int> and mult2 expects an int, the types don’t match and we get a compilation error. We could of course, simply access the ‘Value’ parameter like this:

Func<int, Identity<int>> add2Mult2 = x => mult2(add2(x).Value);

This works fine. The problem is that we need to write x.Value wherever we’re composing any function of Identity<T>. Don’t forget Identity<T> is the simplest possible amplified type we could think of, in fact it’s completely useless. As soon as we want to use anything useful like IEnumerable<T> or Task<T> or IMightThrowAnException<T>, we’re back to obfuscating our code with huge amounts of boiler plate. Getting rid of that boiler plate is the reason we are here in the first place. We need to lose x.Value, but how?

What we need is a function that lets us compose add2 and mult2. Let’s call this function ‘Bind’. Looking at the example above that won’t compile, we can see what the signature of Bind should be. It needs to take the result of add2, an Identity<int> and mult2 a Func<int, Identity<int>> and return an Identity<int>. To make bind more useful, we’ll give it generic parameters. It would also be nice to write it as an extension method:

// a function 'Bind', that allows us to compose Identity returning functions
public static Identity<B> Bind<A, B>(this Identity<A> a, Func<A, Identity<B>> func)
{
return func(a.Value);
}

Of course the body of Bind simply calls a.Value and passes the result to func. We’ve wrapped x.Value with Bind. The beauty of it is that while the mechanism of dealing with an amplified type depends on the nature of the amplified type, the signature of Bind is always the same.

Now we can compose add2 and mult2:

Func<int, Identity<int>> add2Mult2 = x => add2(x).Bind(mult2);

We can use our new composed function like this:

var r1 = add2Mult2(5);
Console.Out.WriteLine("r1.Value = {0}", r1.Value);

Which prints:

r1.Value = 14

Let’s create another useful extension method, ToIdentity, to create a new identity:

public static Identity<T> ToIdentity<T>(this T value)
{
return new Identity<T>(value);
}

Now we can write arbitrarily complex expressions with various identity values:

var result = 
"Hello World!".ToIdentity().Bind( a =>
7.ToIdentity().Bind( b =>
(new DateTime(2010, 1, 11)).ToIdentity().Bind( c =>
(a + ", " + b.ToString() + ", " + c.ToShortDateString())
.ToIdentity())));

Console.WriteLine(result.Value);

Which outputs:

Hello World!, 7, 11/01/2010

Here we’re taking a string, ‘Hello World!’, turning it into an Identity<string>. turning an int, 7, into an Identity<int>, and a DateTime into an Identity<DateTime>. We are then using Bind to magically access the wrapped values, concatenate them and turn them back into an Identity<string>.

OK, that code isn’t the prettiest thing you’ve ever seen I’ll admit. But look at it again. We’ve taken various different types of amplified values, and done some operation on them without ever having to access the ‘Value’ parameter of Identity<T> (except of course when we output the result to the console). This is the key. It’s hard to see the benefit here when the lambda soup is far hairier than simply accessing x.Value, but remember these two facts: First we can remove the lambda soup, that will come later in the series, and second, Identity is the simplest possible example of an amplified type. There is no limit to the complexity we can implement.

Identity<T> is a Monad. The properties of a Monad are that it has a type constructor (Identity<T> itself) and two methods: our ‘Bind’ and ‘ToIdentity’. That’s it, that’s all there is to it.

You will find Bind and ToIdentity called various names depending on the programming language you are using, ToIdentity is called ‘return’ in Haskell and Bind goes by the name of SelectMany in C# as we will see later. It doesn’t really matter what they are called, the important thing is that they have the right signatures:

Bind: Func<Identity<A>, Func<A, Identity<B>>, Identity<B>>
ToIdentity: Func<T, Identity<T>>

Bind is where we express the functionality of our Monad. The magic of Monads is that it’s the only place where we have to express that functionality. It turns out to be a very powerful abstraction.

In the next post we will see how renaming Bind to ‘SelectMany’, and combining it with ToIdentity will allow us to use our Identity<T> Monad with Linq syntax. Stay tuned lambda lovers ;)

Sunday, January 09, 2011

Monads in C#–2. What’s the point?

This is the second part of my Monad series. See the introduction for a list of all the posts.

I made a big claim in part 1, that Monads are “an extraordinarily powerful concept”, without in any way backing it up. So before going on to explain what Monads are and how they work, I should attempt to define the problem they are trying to solve. The difficulty is that they are a kind of ‘meta solution’ to a whole range of programming problems. It’s difficult to explain the problem they are trying to solve without being, on the one hand, too specific and leaving the reader with the impression that they only solve that one problem, or, on the other, so general that it just sounds like a load of mysterious hand waving. I’m going to go for the later now, in the hope that I can bring us back down to earth with some specific examples later in the series.

A Monad is a pattern for doing function composition with ‘amplified’ types. You can think of an amplified type as a generic type with a single type parameter. IEnumerable<T> is a very good example. Monads provide techniques for removing repetitive and awkward code and can allow us to significantly simplify many programming problems. Historically Monads emerged from a branch of mathematics, Category Theory. They were first used in computing by the designers of the Haskell programming language to elegantly introduce side-effecting functions into the ‘pure’ Haskell type system. You don’t need to understand Category Theory (I certainly don’t), or Haskell to understand and use Monads.

Usually, when we program, we manipulate values. These can be simple types, built into the language, like ‘int’, ‘bool’ or ‘string’, or more complex types we define ourselves, like ‘Customer’. We pass these around and do various things with them. The nicest kind of programming is when our programming language lets us express nicely what we are hoping to achieve:

bool IsGreaterThanTen(int value)
{
return value > 10;
}

We can use this really easily:

if(IsGreaterThanTen(x)) {
// do something
}

But what if our function throws an exception?

bool IsAFactorOfTwelve(int value)
{
if(value == 0) throw new Exception("Can't divide by zero");
return (12 % value) == 0;
}

Now we have to surround our use of this function with some boiler-plate code; a try-catch block:

try
{
if(IsAFactorOfTwelve(x))
{
// do something
}
}
catch(Exception e)
{
// handle the exception
}

What if our function could return null? (yes, I know these examples are pretty silly, but you get the point)

string Trim(string value)
{
if (value == null) return null;
return value.Trim();
}

Now we have to insert some more boiler-plate to check for null:

var trimmedValue = Trim(inputValue);
if (trimmedValue == null)
{
// so something different here
}

Every time we have to insert boiler-plate code we obscure what we are really trying to achieve. This make our programmes harder to write, harder to read and gives us plenty of opportunities for creating bugs. Boiler-plate is any code that is not the declaration of what we are trying to achieve. It’s the try-catch blocks, the null checks, the iterations. It’s the stuff that makes us violate DRY.

Here’s a more revealing example. what about dealing with lists or collections (if we didn’t have LINQ or its associated extension methods - there’s a very good reason I’m ruling out using these ;) )? Any time we’re faced with an IEnumerable<T> or an IList<T> we shove in a foreach loop:

foreach (var number in Range(5, 10))
{
// do something with the number
}

That’s more boiler plate.

IEnumerable<int> is interesting. Of course it’s a generic type, but we can also think of it as an ‘amplified’ type. We take an int and turn it into a super int, one that, rather than representing a single integer value, represents a whole load of them.

We can represent other things with ‘amplified types’. In the Trim example above we could have returned a Nullable<string> (except we can’t of course because Nullable<T> can only be used with value types), we would have been amplifying string to say that, as well as being a string, it can also be not-a-string, but null. Of course this is implicit for all reference types in C#, which is a shame, it would be nicer if we could decide if we wanted nullability or not.

We could also imagine that our IsAFactorOfTwelve function could have returned an IMightThrowAnException<bool>. It would certainly have been more explicit and intention revealing. It would have returned a super-bool, one that’s a bool value, but may alternatively be an exception. Of course in C# all functions have an implicit Exception return type, this is also a shame, since C# function signatures tell us nothing about any exceptions they might throw.

Monads give us a way of dealing with these ‘amplified types’ and allow us to remove the boiler plate. They can help us write declarative programs where what we are trying to achieve is not obscured by the apparatus we need to achieve it. They help with our core problem as programmers, getting complexity under control so that we can reason effectively about our code.

In part 3 we’ll meet some real Monads and get them to do some simple tricks. Stay tuned.

Monads in C#–1. Introduction

Here’s the complete series:
1. Introduction.
2. What’s the point?
3. Creating our first Monad.
4. Linq loves Monads.
5. Maybe ;)
6. Introducing a simple parser.
7. Turning our parser into a Monad.
8. Monads in C#-8. Video of my DDD9 Monad talk

I’ve foolishly volunteered to give a talk at DDD9 on the 29th January: ‘Monads! What are they, and why should I care?’:

“Or: How to bend Linq syntax to your will.

These days, monads are the "celebrities of programming language theory". But they also inspire fear in the hearts of lowly imperative programmers like myself. However they are a very useful and powerful abstraction and they pop up everywhere. C#'s Linq syntax is Monadic, for example. Having an understanding of Monads will give you the conceptual tools to greatly simplify many programming challenges, from dealing with nulls and managing state, to asynchronous programming and parsing. This talk will be mostly C#, but I will also be introducing a little F# and even some Haskell.”

Why foolish? Well, firstly, because I’ve only recently come to a limited understanding of what Monads are myself, and I’m fully aware that I’ve got a great deal more to learn. There’s a very good chance that I might not understand some important points, or that I’m just wrong about some things. Secondly, because it’s taken me several books, a gazillion blog posts and articles and upwards of a year to get to my limited understanding. To expect to transfer this to someone else’s brain in an hour’s presentation is completely unrealistic.

So why do it? Simply because Monads are such an extraordinarily powerful concept. I’ve had my mind blown. I’ve been on a wonderful intellectual voyage of discovery this past year, and I want to get other people excited about Monads and functional programming in general. Few people seem to be talking about Monads in the C# community which is a shame. Maybe I can correct that in some small way.  I hope that the people who come along to the talk will get something useful out of it. I don’t expect for someone who’s never come across the concept before to walk out with a real understanding, but maybe they will walk out motivated to learn more with some pointers about where to look. Maybe someone who’s spent some time looking at Monads, but not quite grasped them yet, will find some more pieces of the puzzle? And lastly, and rather selfishly, I’m hoping that by publically explaining my understanding, I will get some feedback and garner insights from people who understand the concept far better than I.

To get my own thoughts in order and provide a starting point for anyone else who’s interested, I’m going to write a series of posts about Monads in C#. This is another foolhardy enterprise as Brent Yorgey so eloquently points out. But so long as you take it in the spirit that everything in this blog should be taken; that it’s just me learning in public, we should get along fine :)

Sunday, January 02, 2011

2010 A Code Rant Retrospective

It’s always nice to look back at the year that’s been, so here’s my personal review of 2010.

Work

The ‘earning money’ part of my life split neatly into two phases this year. One where I earned money, and one when I didn’t.

Up to the end of July I had one client, the UK Pensions Regulator. I was acting ‘Technical Architect’ for their development team. This was a great opportunity that allowed me to implement some very cool technology, but more importantly to learn a great deal more about leading and mentoring teams. Peter, who heads the development department there, was very brave, allowing me to pretty much execute my entire strategic plan, Mwuuhahahaha!!

We had some significant successes. We implemented a message based strategic architecture for application integration, a single-sign-on implementation for all our internal and external systems and a completely new case management system at a fraction of the cost of the COTS alternatives. We also introduced a new focus on code quality with plenty of workshops and code reviews as well as monthly code quality reports. This saw a significant improvement over the the year or so that I was with TPR. I also learnt that sometimes, even when I know I’m right, it doesn’t always pay to point it out :)

For the rest of the year I had a lot of fun with a number of smaller projects. I spent a considerable amount of time making improvements to Suteki Shop and also found time to implement a little idea for a kid’s pocket money bank, Tardis Bank. Since December I’ve been back with a previous client of mine, Embassy CES, where I’m spending most of my time building AJAX based enhancements to their website, which means that I’m at last learning to write Javascript properly :p

My longer term plan is still to try and become more of a micro software house and less of a daily rate contractor. I love delivering bespoke software to spec and I really need to spend more time marketing myself as someone who can do that.

Brighton ALT.NET

Early this year, I took over running Brighton ALT.NET Beers, a monthly get together for Brighton and Sussex net-heads. We’ve have some great discussions over the year and I’ve learnt a ton of stuff from some very clever people. It’s been really nice to discover how many excellent .NET devs there are in the area, and I don’t think we’ve smoked them all out yet either. First Tuesday every month, come along, the next one is on the 4th of January.

Code Rant

The response I get to this blog continues to amaze me. For some reason it just keeps on getting more and more popular. I regularly get upwards of a thousand visits a day and I get fantastic feedback both on the comments and via twitter. Thanks to all of you for reading and commenting, it makes it such a pleasure to write!

The Code Rant year started off with a long and never completed series on Windsor: 10 Advanced Windsor Tricks. This also appeared as a 4 hour workshop at this year’s Progressive .NET Tutorials. I’ve well and truly roasted Windsor now, and I should either put-up or shut-up; start contributing properly to the code and documentation, which I don’t really have time for, or move on to other interests. I’ll keep blogging about containers as the mood takes me, but I doubt if I’ll do any more speaking about them.

I continued my fascination with functional programming and came as close as I ever will do to contributing to Windsor when I did a brief spike for a currying facility.

I do mostly web based work and spend most of my time in the ASP.NET MVC framework so of course I continued to blog about various bits and pieces. My experimental MVC Add-Ins got the best response, including a great contribution from Krzysztof. Even though I still do all my web work in ASP.NET MVC, I’ve become very interested in the explosion in alternative .NET web frameworks.

I blogged about my experiences writing Tardis Bank, especially using ASP.NET MVC and RavenDb together, as well as RavenDb in general.

Another core tool that I spend plenty of time with is NHiberante. I wrote about Get vs Load, testing mappings and  schema export.

But of course, the raison d'ĂȘtre of Code Rant is to RANT! write considered and unbiased commentary. Here are some choice bits of depressurisation from 2010:
Why I Write This Stuff
Is Microsoft the IBM of the 2010’s?
You Don’t Need an Application Server
How To Fix Public Sector IT
Trust Your Instincts, or how to stay interested in programming

What I’ve learnt

The greatest intellectual pleasure I’ve had this year was reading Brian O’Sullivan’s Read World Haskell. I’ve always been interested in programming as an art or science in its own right. Haskell is at the cutting edge of programming language research and this book shows how advanced programming features can help solve real world problems. There’s currently no prospect of being paid real money to write Haskell code, but the lessons I’m learning are feeding directly into my C# programming and I strongly suspect that I’ll be writing F# in anger soon. In fact I expect that’ll be the big change in next year’s retrospective. I’m still struggling at the foothills of functional, but at last I can say that I understand what a Monad is, and if you want a preview of Code Rant 2011, I can safely say, expect a lot more functional.