What is it about

This project brings some features from functional languages, like pattern matching, collection unfold or partial function application to C# and extends the possibilities of functional programming in C#. It's available as C# library.
Download: FunctionalProgramming v1.0

Examples

Collection unfold:

var incrementsToTen = LazyCollection.Unfold(
            x =>
               {
                  if (x <= 10)
                  {
                     return Option.Some(x, x + 1);
                  }
                  else
                  {
                     return Option.None<int, int>;
                  }
               }, 
            3);

Partial function application:

Func<int, int, int, int, int> sum = (w, x, y, z) => w + x + y + z;

var sumWithFour = PartialApplicator.Apply(sum, 4);
var sumWithFourAndFive = PartialApplicator.Apply(sumWithFour, 5);
var sumResult = PartialApplicator.Apply(sumWithFourAndFive, 6, 7);

Console.WriteLine(sumResult); // 22

Pattern matching over collections:

private static void PrintCollection(IEnumerable<int> collectionToProcess)
{
    PatternMatcher.MatchCollection(collectionToProcess)
      .ElementsAndRest(rest =>
                            {
                                Console.WriteLine("Lucky 7 found");
                                PrintCollection(rest);
                            }, 7)
      .NumberOfElementsAndRest((elements, rest) =>
                                    {
                                        Console.WriteLine(
                                           "{0} and {1} found", 
                                           elements[0], elements[1]);
                                        PrintCollection(rest);
                                    }, 2)
      .HeadAndRest((head, rest) =>
                        {
                            Console.WriteLine("{0} found", head);
                            PrintCollection(rest);
                        })
      .Empty(() => Console.WriteLine("End of collection reached!"))
        .DoMatching();
}

List<int> inputCollection = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
PrintCollection(inputCollection);

// Output:
// 1 and 2 found
// 3 and 4 found
// 5 and 6 found
// Lucky 7 found
// 8 and 9 found
// 10 and 11 found
// 12 found
// End of collection reached!

Documentation

Full XML help is available in FunctionalProgramming v1.0 package.

Last edited Apr 22, 2012 at 10:24 AM by Lotarik, version 6