Skip to content

Instantly share code, notes, and snippets.

@T4rk1n
Last active May 6, 2017 01:10
Show Gist options
  • Save T4rk1n/ffbc9ed77acb45f289cb7667d10a0e7c to your computer and use it in GitHub Desktop.
Save T4rk1n/ffbc9ed77acb45f289cb7667d10a0e7c to your computer and use it in GitHub Desktop.
Map, Filter, Reduce.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace FunctionalCSharp
{
internal class Program
{
public static void Main(string[] args)
{
// Quick tests
var listInt = new List<int>(Enumerable.Range(1, 20).Filter(x => x % 2 == 0).Map(x => x + 1));
foreach (var mapped in listInt)
{
Console.Out.WriteLine("mapped = {0}", mapped);
}
Console.Out.WriteLine("reduction = {0}", listInt.Reduce((acc, x) => acc + x, 0));
}
}
/// <summary>
/// Extensions for IEnumerable Map, Filter, Reduce.
/// </summary>
public static class FunctionalExtensions
{
public delegate TOutput MapFunc<in TInput, out TOutput>(TInput input);
public delegate bool FilterFunc<in T>(T o);
public delegate TOutput ReduceFunc<in TInput, TOutput>(TOutput accumulator, TInput o);
/// <summary>
/// Apply a mapping function.
/// </summary>
/// <param name="enumerable"></param>
/// <param name="mapper"></param>
/// <typeparam name="TInput">The type of the input IEnumerable.</typeparam>
/// <typeparam name="TOutput">The output type of the mapping function.</typeparam>
/// <returns></returns>
public static IEnumerable<TOutput> Map<TInput, TOutput>(this IEnumerable<TInput> enumerable, MapFunc<TInput, TOutput> mapper)
{
foreach (var toMap in enumerable)
{
yield return mapper(toMap);
}
}
/// <summary>
/// Apply a filter function to an IEnumerable
/// </summary>
/// <param name="enumerable"></param>
/// <param name="filter"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<T> Filter<T>(this IEnumerable<T> enumerable, FilterFunc<T> filter)
{
foreach (var toFilter in enumerable)
{
if (filter(toFilter)) yield return toFilter;
}
}
/// <summary>
/// Reduce every entry and return a single value.
/// </summary>
/// <param name="enumerable"></param>
/// <param name="reduce"></param>
/// <param name="accumulator"></param>
/// <typeparam name="TInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
/// <returns></returns>
public static TOutput Reduce<TInput, TOutput>(this IEnumerable<TInput> enumerable, ReduceFunc<TInput, TOutput> reduce, TOutput accumulator)
{
foreach (var toReduce in enumerable)
{
accumulator = reduce(accumulator, toReduce);
}
return accumulator;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment