Barry Faassen created a nice example using new C# which allows to make things like e.g. cartesian-product Cartesian Product of 2 arrays very easy:
Code Block | ||||
---|---|---|---|---|
| ||||
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SeqMapFunctionalProgrammingInCSharp { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 3, 4, 5 }; var r1 = a.Map(x => x * x ); var r2 = a.Map(b, (x, y) => x + y); var r3 = a.CartesianProduct(b, (x, y) => x * y); foreach (var item in r2) Console.WriteLine(item); } } public static class Seq { public static IEnumerable<T> Map<T>(this IEnumerable<T> a, Func<T, T> fun) { foreach (var x in a) yield return fun(x); } public static IEnumerable<T> Map<T>(this IEnumerable<T> a, IEnumerable<T> b, Func<T, T, T> fun) { int i = 0; foreach (var x in a) yield return fun(x, b.ElementAt(i++)); } public static IEnumerable<T> CartesianProduct<T>(this IEnumerable<T> a, IEnumerable<T> b, Func<T, T, T> fun) { foreach (var x in a) foreach (var y in b) yield return fun(x, y); } } } |