Juan Wajnerman

Juan Wajnerman

Generic functors and type inference

2 min
Apr 20 2004
.NET
2 min
Apr 20 2004


C# 2.0 has some features that I see as functional programming features, like anonymous delegates that can be used as "functors" and closure methods in ''Array'' and ''IList'' classes. Also, some kind of type inference is included when using generics. Here is an example:

string[] ss = new string[] { "One", "Two", "Three" };
Array.ForEach(ss, delegate(string s)
{
Console.WriteLine(s);
});

There is no need here to specify the type for the ForEach generic method. It's infered from parameters, like (really cool!) funcional languages as OCaml or SML does.

However the inference isn't complete. This will fail because the type cannot be infered from return types :(

string[] ss = new string[] { "1", "2", "3" };
int[] nn = Array.ConvertAll(ss, delegate(string s)
{
return int.Parse(s);
});

Despite of this, all those features are welcomed including closure methods and "functors" delegates like ''Action'', ''Converter'' and ''Predicate''.