Friday, February 7, 2014

Functional C# - insight by Python

Python has many powerful functions. I realized there are many similar functions available in .NET.

Enumerable.Aggregate
Function Description .NET
zip Pairs iterables element by element:

* x = [1, 2, 3]
* y = [4, 5, 6]
* zipped = zip(x, y)
* zipped
[(1, 4), (2, 5), (3, 6)]

Enumerable.Zip

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = 
    numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// 1 one 
// 2 two 
// 3 three

reduce Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates
((((1+2)+3)+4)+5)
.
Enumerable.Aggregate

string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words. 
string[] words = sentence.Split(' ');

// Prepend each word to the beginning of the  
// new sentence to reverse the word order. 
string reversed = words.Aggregate((workingSentence, next) =>
                                                  next + " " + workingSentence);

// dog lazy the over jumps fox brown quick the 
filterConstruct a list from those elements of iterable for which function returns true.

filter(lambda x: x%2, range(10)) 
result: 1 3 5 7 9
Enumerable.Where
List fruits =
new List { "apple", "passionfruit", "banana", "mango", 
    "orange", "blueberry", "grape", "strawberry" };

IEnumerable query = fruits.Where(fruit => fruit.Length < 6);

/*
This code produces the following output:

apple
mango
grape
*/