0

Currying in C#

by klh 7. januar 2009 06:12

I recently listend to Deep Fried Bytes on functional programming in C#.

In the show notes, there is a code sample of doing curring in C#, I worked a bit further on it.

This is what came out of it:

First I did a delegate, that would take a delegate:

Func<Func<int, int, int>, int, Func<int, int>> MyCurry =                
(dele, x) => z => dele(z, x);

Then I made three functions, that would adhere to Func<int, int, int> :

Func<int, int, int> add = (x, y) => x + y;
Func<int, int, int> sub = (x, y) => x - y;
Func<int, int, int> mul = (x, y) => x * y;

Then I made three curried functions, that used the first delegate:

var add9 = MyCurry(add, 9);
var sub9 = MyCurry(sub, 9);
var mulBy2 = MyCurry(mul, 2);

And lastly I used the curried functions:

int result = add9(5);
result = sub9(10);
result = mulBy2(5);

And it actually works!

This way it is really easy to curry functions together…

  kick it on DotNetKicks.com

Tags:

Kommentarer

Tilføj kommentar


(Viser dit Gravatar icon)  

  Country flag

biuquote
  • Kommentar
  • Eksempel
Loading



Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft