Saturday, March 8, 2014

In Search of Maybe in C# - Part III

Following up on the last two posts[1, 2] this final post in my little series on Maybe/Option gives a third implementation of Option. This time around I'll drop the idea of letting Option implement IEnumerable and instead focus on implementing the function needed to make my Option a monad (which it wasn't actually in the last post).

First off let's reiterate the basic implementation of Option - a simple class that can be in two states 'Some' or 'None', where Options in 'Some' state contain a value and Option in 'None' state don't.

I also want to maintain the matching functionality that I had  in the other posts, so I'm keeping this:

While even this is somewhat useful as is, it becomes better if we add the remaining part of the monad; the FlatMap function (the unit function is the Some(T value) method, so only FlatMap aka Bind aka SelectMany is missing). So we add this to the OptionHelpers class:

This is nice because now we are once again able to chain operations without having to worry much about null ref exceptions.
Just for convenience I'll throw in a Filter function in the OptionHelpers as well:


To exemplify how Option can flow through a series of operations take a look at the following where there is a value,so the some case will flow through:

In the case of no value the none case will flow through as in this example:



Towards the end of the first post in the series I mentioned that it's nice to be able to treat Option as a collection. That led to Option implementing IEnumerable in the second post, thus enabling passing Options into existing code working on IEnumerables, which is quite useful when introducing Option into an existing code base. Especially so, if it's a code base that uses LINQ a lot. In such code you're likely to find functions accepting an IEnumerable and returning an IEnumerable. An Option type implementing IEnumerable fits rigth in. On the other hand, if you don't have exiting LINQ based code to fit into, the Option version in this post is maybe a bit simpler to work with because it has smaller API surface and it still provides the benefit of allowing chaining.

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.

Wednesday, January 29, 2014

In Search of Maybe in C#

One of the things working in Scala has taught me about C# is that the maybe monad is nicer than null.

In case you're not sure what the maybe monad is: It's a generic type that either contains a value or not. In Scala as well as in F# this type is called Option and can be either Some - in which case it contains a value - or None - in which case it doesn't. This allows you to represent the absence of a value in an explicit way visible to the compiler, since Option<T> is a separate type from T. This turns out to be a whole lot stronger than relying on null to represent the absence of a value. I'll point you to an article about F#'s Option for more explanation on why.

Functional languages will usually let you pattern match over Option, making it very easy to clearly differentiate the case of Some from the case of None. In F# this look like so:


In C# we don't have this. The closest thing is Nullable<T>, but that doesn't work over reference types. But is Nullable<T> really the closest thing in C# to Option? - NO. As was pointed out to me in a recent email exchange the F# Option type is available in C# too.

Let's see if we can redo the above F# code in C#. First the declaration the name variable:


The F# Option type is part of the FSharp.Core assembly and the is actually called FSharpOption. Hence the line above.
On to the nameOrApology variable:


Not nearly as clear as the F# counterpart. What's in the if part; what's in the else part. Not nearly as clear to me as the pattern matching in F#.
We can do better, using this little helper extension function:


Which let's us initialize nameOrApology like this:


Now the two outcomes - a value inside the Option or no value - are much more clear to me.

This is OK. Although the name, FSharpOption, is not too nice. Some of the method names - e.g. get_IsSome - aren't nice either. More importantly: Another thing Scala taught me is that it's nice if Option can be used in place of a collection. But that's for another post.