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

- Partial application in F# and C#
- Why do we need partial application? Ã¢â‚¬â€œ Part 1 of n Ã¢â‚¬â€œ Fluent interfaces and piping
- Currying and uncurrying in C# and F#

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: C-Sharp, Currying, F#, partial application, type classes