Rash thoughts about .NET, C#, F# and Dynamics NAV.

"Every solution will only lead to new problems."

Tuesday, 31. January 2012

Why do we need partial application? – Part 2 of n – Simulating type classes in C# and F#

Filed under: C#,F# — Steffen Forkmann at 16:48 Uhr

This is yet another blog post in my Currying and Partial application series. This is what I have posted so far:

In this post I want to show you a way to simulate type classes in C# and F#. Type classes are this wonderful feature in Haskell which allow you to specify constraints on your polymorphic types. We don’t have this in C# nor F#.

Let’s start with the following problem: We want to compute the sum of the squares of arbitrary numbers. We want to write something like this:


The problem is we don’t have a generic * function and of course we’d also need a generic + operator and maybe a generic zero. Obviously we need a constraint on the generic parameter T since + might not be defined for any type. So let’s define an interface for numbers:

Nothing special here, so let’s get straight to the implementation for integers and doubles:

So far so good. With this in our pocket we rewrite SumOfSquares() into this:

The trick is that we pass the concrete implementation as the first parameter into our function. This works exactly like a type constraint or as Simon Peyton-Jones would say: the vtable travels into the function. Notice that we don’t have access to the definition of in nor double. There is no way for us to express that int or double implement a number interface.

Now let’s try this out:

As you can see, this is perfectly type safe. We now have a way for poor man’s type classes in C#. Yay!

Now what has this to do with partial application? Let’s look at the same thing in F#:

We’re using a lot of partial application here. Exercise: Try to spot all the places.

Ok, you’re right. This post might be a little bit far away from the partial application stuff, but it’s still related. Somehow.

Tags: , , , ,