Tuesday, February 22, 2011

Brighton ALT.NET show and tell night videos

Back on the 1st February we had a show and tell night at Brighton ALT.NET – Thanks to Keith Bloom, who brought his video camera along and then went through the painful process of uploading them all to Vimeo, we can now present the show and tell videos:

Steve Mason - N2 CMS

A quick tour of the best open source CMS on the planet. Homepage - http://n2cms.com/ Source code - http://github.com/n2cms/n2cms/ (the Google code & codeplex repositories are old & unused) Discussions - http://n2cms.codeplex.com/discussions

Andrew Cherry - Socket Machine

A .NET server toolkit that you can use to build any socket based server on .NET with a very nice fluent API. The source will be opened up soon on Github, for now follow @socketmachine - announcements etc. will always be there from now on. Code will be published under the xyncro org on Github (https://github.com/xyncro) but be aware that there is nothing currently there now - this is intentional.

Jay Kannan - Kinect in .NET

Using the Kinect to control .NET applications. the demo concentrated on a Game Environment using the XNA platform and 3D physics for creating and bouncing bubbles around the screen. a long way to go to make it usable. the Kinect is clearly the best Augmented reality / motion control platform of choice for Kiosk makers and for public user interaction. look at the links below for more information. Kinect Hacks. PrimeSense OpenNI - this is the official library from the CHipset guys that I'm using. OpenKinect. Code Laboratories.

Michael Steele - Netduino

blog My introductory blog for netduino - will update with the burglar alarm & operation game
Netduino forum
.Net Micro Framework
tinyclr Fez community website - Another board running .Net Micro Framework
Scott Hanselman Micro Framework/Netduino podcasts
Build Brighton meet every Thursday at The Skiff to tinker with electronics.

Me - Monads in C#

This is a very compressed, and probably meaningless 15 minute version of my hour long DDD9 talk. Session code on github. The Monad Wikipedia page is excellent, if somewhat intimidating. The references and external links are an excellent starting point for further investigation.

Paul Hazells - Can twitter predict the stock market?

Unfortunately, Keith's video recorder died by this point, so we don't have Paul's excellent session. Very sorry Paul. But here are the links:

http://aws.amazon.com/free/ - AWS Free Usage Tier
http://nodejs.org/ - node.js
https://github.com/isaacs/npm - npm (node package manager)
https://github.com/technoweenie/twitter-node - twitter-node
https://github.com/indexzero/forever - forever
http://omnipotent.net/jquery.sparkline/ - sparklines (for the graphs)
http://html5boilerplate.com/ I forgot to mention the HTML5 boilerplate which I've also used. I saw a few of the group at the DDD9 talk on this so thought it might be of interest. I'd definitely recommend it for new projects, especially if you need to support older browsers.

If you have any questions or comments, please do not hesitate to ask me either at a meeting or via twitter: @paulhazells

Thursday, February 17, 2011

Monads in C#-8. Video of my DDD9 Monad talk

This is the eighth 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.

Last month I gave a talk at DDD9 loosely based on this series: Monads! What are they and why should I care.

Note: The talk (and audio) starts at 6 minutes into the video.

Mike Hadlow - Monads! What are they and why should I care? - DeveloperDeveloperDeveloper 9 from Phil Winstanley on Vimeo.

Enjoy!

Tuesday, February 15, 2011

Delegates make great container components

The problem with object oriented languages is that you often have to wrap up single functions in a class even when there’s no real reason for that class to exist. This is especially true for many ‘service’ classes. For example, for a long time I used to have something like this in most of my projects:

public interface IDateProvider
{
DateTime Now();
}
public class DateProvider : IDateProvider
{
public DateTime Now()
{
return DateTime.Now();
}
}

I would register my DateProvider with Windsor like this:

container.Regisgter(
Component.For<IDateProvider>().ImplementedBy<DateProvider>()
);

Being able to set the current time in unit tests is essential if you’re doing any kind of logic that does date computations, and this served me well. But it’s a lot of boiler plate just to get the current date. It also means that I have to build a mock IDateProvider for my unit tests and set stubs on it – more irritating boiler plate.

But C# is also quite a good functional language and Windsor deals with delegates just as easily as it deals with interfaces. These days I no longer have an IDateProvider, but just a simple delegate:

public delegate DateTime Now();

Which I register like this:

container.Register(
Component.For<Now>().Instance(() => DateTime.Now),
);

Now any component that needs to know the current DateTime value simply has a dependency on the Now delegate:

public class MyComponent
{
private readonly Now now;
public MyComponent(Now now)
{
this.now = now;
}
public void DoSomething()
{
var currentTime = now();
....
}
}

And it’s really easy to stub out for unit tests:

var now = new DateTime(2010, 2, 15);
var myComponent = new MyComponent(() => now);
myComponent.DoSomething();

This is also a great way for providing infrastructure services when your infrastructure isn’t IoC container friendly. How about this:

public delegate string CurrentUser();

...

container.Register(
Component.For<CurrentUser>().Instance(() => HttpContext.Current.User.Identity.Name)
);

In some ways delegates are more flexible than interfaces since you don’t have to declare that a particular lambda or method implements the delegate, so long as the signature matches you’re good.

Indeed, if Windsor did currying we could probably remove most of our service classes and simply write our software as static methods. But that’s another blog post ;)

Sunday, February 13, 2011

Using Git alongside other version control systems

I love Git. If you haven’t yet discovered the awesomeness of distributed version control, you are really missing out. Git is now the version control system of choice for a huge number of open source projects. That’s probably got a lot to do with GitHub, the best cloud based version control system on the planet, but the ease with which you can branch and merge with Git is also a major factor.

But even if you’re not building open source software development in the cloud, even if you’re stuck in some enterprise shop with TFS, you can still use the power of Git’s branching and merging to help you get your work done. Because Git is a distributed version control system it makes it trivial to set up a local repository. You can use that local repository create small local branches for particular features and to help you merge them together before you make a big check-in to your corporate VCS.

The trick to getting Git to work well in this scenario is to make sure that Git and your main VCS ignore each other.

For example, I’m still using subversion and Google Code for Suteki Shop. Yes, I know I should move it over to Git and GitHub, but I’m lazy and I quite like the Google Code project page, so I haven’t had the time or the inclination to do it yet. But I use Git locally to manage small changes. To get Git and subversion to ignore each other is pretty easy. Git places its repository in a folder in the root of your project called ‘.git’. I just ask subversion to ignore that folder. Using TortoiseSVN you do it like this:

svnignore

Getting Git to ignore subversion is similarly easy. Subversion tracks its status using files in an ‘.svn’ folder in each folder under source control, so I simply add ‘.svn’ to my .gitignore file:

Here’s my .gitignore file:

[Oo]bj
[Bb]in
*.user
*.suo
*.[Cc]ache
*.bak
*.ncb
*.log
*.DS_Store
[Tt]humbs.db
_ReSharper.*
.svn

I’m currently working on a stock control addin for Suteki Shop. While I was writing it I came across a bad design choice that I made in the past that stopped me from being able to properly decouple my addin from the core Suteki Shop project. Rather than executing a large refactoring directly in my stock control branch, I created a new branch from master, refactored away my bad design, tested it, merged it back into master and committed it to svn without having had to change or commit my in-progress work on stock control.

This ability to go off on tangents without one piece interfering with another is very powerful. It gives you the confidence to make very radical experimental changes that would have seemed like too much of a commitment previously.

Thursday, February 10, 2011

Monads in C#-7. Turning our parser into a Monad

This is the seventh 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.

Do you remember our parser delegate from part 6? If you haven’t read it yet, I’d recommend reviewing it now before reading the rest of this post.

public delegate Maybe<Tuple<T, string>> Parser<T>(string input);

Remember the pain we had to go through to combine these parsers? Let’s try a different approach by turning our parser into a Monad. Up to now we’ve just looked at turning classes or interfaces with a single type parameter into Monads, but we can do just the same with a delegate.

First let’s write a ToParser method. It’s pretty easy we just return a parser that returns our item without consuming any of the input string:

public static Parser<T> ToParser<T>(this T value)
{
return s => new Just<Tuple<T, string>>(Tuple.Create(value, s));
}

Next we need a Bind method. This is a little harder to write, but if we ‘follow the types’ it appears relatively painlessly. Let’s think about the signature of bind, remember this is the same for any Monad:

public static Parser<B> Bind<A, B>(this Parser<A> a, Func<A, Parser<B>> func){}

Now we’ll digest the signature step by step. First let’s look at the return type: Parser<B>.  Remember Parser<B> is a function from a string to a Maybe<Tuple<B, string>>, so we need to return a lambda for that function:

public static Parser<B> Bind<A, B>(this Parser<A> a, Func<A, Parser<B>> func)
{
return s =>
{
// ...
};
}

That lambda needs to return a Maybe<Tuple<B, string>>, we can get one of those by invoking func, getting the returned Parser<B> and invoking that:

public static Parser<B> Bind<A, B>(this Parser<A> a, Func<A, Parser<B>> func)
{
return s =>
{
var bParser = func( ??? );
return bParser( ??? );
};
}

We need an A to pass to func and we can get one of those by invoking the a parser, getting it’s return value and grabbing the A from that:

public static Parser<B> Bind<A, B>(this Parser<A> a, Func<A, Parser<B>> func)
{
return s =>
{
var aMaybe = a(s);
var aResult = aMaybe as Just<Tuple<A, string>>;

// short circuit if parse fails
if (aResult == null) return new Nothing<Tuple<B, string>>();

var aValue = aResult.Value.Item1;

var bParser = func(aValue);
return bParser( ??? );
};
}

Notice how we short circuit the parse if the a parser fails. This means that any combination of parsers will return Nothing if any one of them can’t parse its part of the input string.

Lastly we need a string value to feed to our bParser, which we can get from the a parser result:

public static Parser<B> Bind<A, B>(this Parser<A> a, Func<A, Parser<B>> func)
{
return s =>
{
var aMaybe = a(s);
var aResult = aMaybe as Just<Tuple<A, string>>;

// short circuit if parse fails
if (aResult == null) return new Nothing<Tuple<B, string>>();

var aValue = aResult.Value.Item1;
var sString = aResult.Value.Item2;

var bParser = func(aValue);
return bParser(sString);
};
}

That’s it, we have built a Monadic parser. To use it with Linq syntax we need to write a SelectMany, but that’s a mechanical operation because we already know what it looks like, it’s exactly the same as the Ident<T> SelectMany and the Maybe<T> SelectMany that we’ve already written, except with Parser<T> substituted:

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

Now we can write our little Hello World parser in three lines of code:

var helloWorldParser =
from hello in "Hello".Find()
from world in "World".Find()
select new {Hello = hello, World = world};

var result = helloWorldParser("HelloWorld");

Console.WriteLine(result.AsString(x => x.Hello));
Console.WriteLine(result.AsString(x => x.World));

// outputs
// Hello
// World

That is a thing of beauty.

Hopefully you can start to see how Monads can let you simply build some very complex systems.

If you want to dig deeper into Monadic parsers, Nicholas Blumhardt has a very nice implementation called Sprache.

Happy Parsing!

Friday, February 04, 2011

AsmSpy: A little tool to help fix assembly version conflicts

Do you ever get these kinds of messages when you compile your project?

------ Build started: Project: Suteki.Shop.CreateDb, Configuration: Debug x86 ------
No way to resolve conflict between "System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
and "System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35". 
Choosing "System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" arbitrarily.
Consider app.config remapping of assembly "NHibernate, Culture=neutral, PublicKeyToken=aa95f207798dfdb4" 
from Version "3.0.0.2001" [] to Version "3.0.0.4000" 
[D:\Source\sutekishop\Suteki.Shop\packages\NHibernate.3.0.0.4000\lib\NHibernate.dll] to solve conflict and get rid of warning.
Consider app.config remapping of assembly "System.Web.Mvc, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
from Version "2.0.0.0" [C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dll] to Version "3.0.0.0" 
[C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll] to solve conflict and get rid of warning.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1360,9): warning MSB3247: 
Found conflicts between different versions of the same dependent assembly.
Suteki.Shop.CreateDb -> D:\Source\sutekishop\Suteki.Shop\Suteki.Shop.CreateDb\bin\Debug\Suteki.Shop.CreateDb.exe

The problem is that the build output doesn’t tell me which of my assemblies references version 2.0.0.0 of System.Web.Mvc and which references version 3.0.0.0.

If you’re writing software using lots of 3rd party assemblies like I do, it’s a constant problem. I’ve written a little bit of code that I drag around with me that outputs lists of assemblies that my assemblies reference. I’ve found it very useful for resolving these kinds of issues.

Now I’ve wrapped it up as a little console app, AsmSpy, and put it on github here:

https://github.com/mikehadlow/AsmSpy

Or you can download a zip file of the compiled tool here:

http://static.mikehadlow.com/AsmSpy.zip

How it works:
Simply run AsmSpy giving it a path to your bin directory (the folder where your project's assemblies live). E.g:

AsmSpy D:\Source\sutekishop\Suteki.Shop\Suteki.Shop\bin

It will output a list of all the assemblies referenced by your assemblies. You can look at the
list to determine where versioining conflicts occur.
 
The output looks something like this:

....
Reference: System.Runtime.Serialization
3.0.0.0 by Microsoft.ServiceModel.Samples.XmlRpc
3.0.0.0 by Microsoft.Web.Mvc
4.0.0.0 by Suteki.Shop
Reference: System.Web.Mvc
2.0.0.0 by Microsoft.Web.Mvc
3.0.0.0 by MvcContrib
3.0.0.0 by MvcContrib.FluentHtml
3.0.0.0 by Suteki.Common
2.0.0.0 by Suteki.Common
3.0.0.0 by Suteki.Shop
2.0.0.0 by Suteki.Shop
Reference: System.ServiceModel.Web
3.5.0.0 by Microsoft.Web.Mvc
Reference: System.Web.Abstractions
3.5.0.0 by Microsoft.Web.Mvc
....

You can see that System.Web.Mvc is referenced by 7 assemblies in my bin folder. Some reference
version 2.0.0.0 and some version 3.0.0.0. I can now resolve any conflicts.

Thursday, February 03, 2011

The MVC 3.0 IDependencyResolver interface is broken. Don’t use it with Windsor.

I’ve been spending today moving Suteki Shop to MVC 3. One of the cool new features of MVC 3 is a much greater focus on allowing the various components (Controllers, Views, Filters etc) to be composed by an IoC container. It’s been possible since MVC 1 to provide your own custom controller factory, but the promise with MVC 3 is that you can provide an implementation of IDependencyResolver that wraps your IoC container of choice, and no longer have to bother about implementing various factory classes.

Here’s IDependencyResolver:

public interface IDependencyResolver {
object GetService(Type serviceType);
IEnumerable<object> GetServices(Type serviceType);
}

But there’s a huge problem with this. Can you spot it? That’s right, no ‘Release’ method. You can provide a service from your IoC container, but there’s no way to clean it up. If I was going to use this in Suteki Shop, I would have a memory leak of epic proportions.

According to the MVC team, this isn’t an issue because they will call ‘Dispose’ on any service that implements IDisposable, but that won’t work in many cases. Let me explain. Say I’ve got a controller like this:

public class HomeController : IController
{
private readonly ICustomerRepository customerRepository;
public HomeController(ICustomerRepository customerRepository)
{
this.customerRepository = customerRepository;
}
// ... does some stuff with customerRepository
}

My controller doesn’t implement IDisposable. So no Dispose method gets called.
 
Now say this is my implementation of ICustomerRepository:
 
public class CustomerRepository : ICustomerRepository, IDisposable
{
// ... etc
}

CustomerRepository does implement IDisposable. But the MVC framework doesn’t know this, indeed my HomeController doesn’t know it either. That’s the whole point of using an IoC container in the first place, it worries about component lifecycles, not the client service. If I resolve HomeController from Windsor it will create all its dependencies and if it finds any that implement IDisposable it will track the entire dependency graph. If I then call ‘Release’ on my HomeController instance, Windsor will know to dispose of CustomerRepository correctly. But if Release is never called CustomerRepository will never get disposed and my web application will gradually consume more and more memory, database connections, file handles, or whatever should have been cleaned up when Dispose gets called.
 
Krzysztof Kozmic has a great post here about how Windsor tracks components. It’s a ‘must read’ if you’re a Windsor user.
 
So the upshot is that all this nice new work in MVC3 is unusable, certainly with Windsor. It’s also a very dangerous trap for the unwary. My advice is that you shouldn’t implement an IDependencyResolver for Windsor. I don’t know how other IoC containers handle releasing components deep in their dependency graph, but I would make sure you understand exactly how they work before going down this route.

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.