My mostly technical blog. An on-line journal of my activity in the IT industry and any other technical interests or techy things that happen to catch my attention.

Wednesday, 18 February 2009

Currying, some examples and comparisons between C# and Scala

I'm back again! It's been some 3 weeks since my last blog - I've been in New York for 5 days and busy either side sorting out commitments and work and home.

So, in this posting I'd like to continue on the theme of Lamda and functional programming with some simple examples of Currying in both C# .Net (3.0+) and Scala.

I've tried to keep the examples equivalent as closely as possible but Scala has a few different options when it comes to syntax, so the Scala version is a little longer as it delves into these extra possibilities.

What is currying?

In a nutshell currying is "the process of reducing a function that takes multiple arguments into a series of functions that each take one argument"

Take the above definition of a method, the this keyword in the (this Func...) parameter definition makes the function an extension method, so it can be used as if it were declared on the add function - to illustrate the point, without the extension syntax the Curry function could only be invoked in the regular way as follows:

var curriedAdd = Curry(add);

As an extension method, it's valid to use the original add.Curry() or Curry(add) syntax interchangeably.

Scala supports curried parameter in {} syntax for functions that appear to extend the language by taking parameter from the body of the call.

Update:

I realised that the way I'd defined the curried add functions in the Scala example is perhaps not as verbose or explicit as it could have been, and therefore perhaps less easy to understand or compare to the C# example. So here is another code snipped that shows a more verbose currying: