Thursday, February 20, 2014

In Search of Maybe in C# - Part II

In my last post I wrote that I'd like to have an implementation of the Maybe monad in C#, and I explored how to use the F# implementation - FSharpOption in C#.

In this post I'll show a quick implementation of Maybe in C#, I'll call it Option - as was noted in some of the comments on the last post this turns out to be quite simple. I left off last time mentioning that it's nice when Option can act somewhat as a collection. That turns out to be easy too. Just watch as I walk through it.

Implementing basic Option
First of all the Option type is a type that can either be Some or None. That is simply:

which allows for creating options like this:

So far so good. This all there is to a basic Maybe monad in C#.

Simulate pattern matching on Option
As argued in the last post I'd like be able to do something similar to pattern matching over my Option type. It's not going be nearly as strong as F#s or Scalas pattern matcing, but it's pretty easy to support these scenarios:

All that takes is adding to simple methods on the Option type that each check the value of the Option instance and calls the right callback. In other words just add these two methods to the Option class above:

That's matching sorted.

Act like a collection
Now I also want Option to be usable as though it was a collection. I want that in order to be able to write chains of linq transformations and then just pass Options through that. To illustrate, I want to able to do this:

This means that Option must now implement IEnumerable<T>, which is done like so:

And to be able to get back an option from a IEnumerable with 0 or 1 element:

which is useful in order to be able to do the matching from above.

All together
Putting it all together the Option type becomes:

Not too hard.