Skip to content

Instantly share code, notes, and snippets.

@scott-fleischman
Created July 20, 2015 23:54
Show Gist options
  • Save scott-fleischman/a2062b94bd50ee06517f to your computer and use it in GitHub Desktop.
Save scott-fleischman/a2062b94bd50ee06517f to your computer and use it in GitHub Desktop.
Gross C# functional stuff
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using static System.Math;
using static Functional;
public static class Functional
{
public static Func<X, Z> Compose<X, Y, Z>(Func<Y, Z> g, Func<X, Y> f) => x => g(f(x));
public static Func<X, Func<Y, Z>> Curry<X, Y, Z>(Func<X, Y, Z> f) => x => y => f(x, y);
public static Func<X, Func<X, X>> CurryUniform<X>(Func<X, X, X> f) => x => y => f(x, y);
public static Func<IEnumerable<X>, IEnumerable<Y>> Map<X, Y>(Func<X, Y> f) => xs => xs.Select(x => f(x));
public static Func<A, Func<IEnumerable<X>, A>> Foldl<X, A>(Func<A, Func<X, A>> f) => a => xs => xs.Aggregate(a, (a2, x2) => f(a2)(x2));
}
public class Program
{
public static void Main()
{
Func<int, string> f = x => x.ToString();
Func<string, Name> g = x => new Name(x);
WriteLine(Compose(g, f)(10));
var pow2 = CurryUniform<double>(Pow)(2.0);
WriteLine(pow2(8));
var plus = CurryUniform<int>((x, y) => x + y);
var values = new[] { 1, 2, 3 };
var results = Map(Compose(x => x.ToString(), plus(2)))(values);
WriteLine(string.Join(", ", results));
var results2 = Compose(Map((int x) => x.ToString()), Map(plus(2)))(values);
WriteLine(string.Join(", ", results));
var sum = Foldl(plus)(0)(values);
WriteLine(sum);
}
}
public class Name
{
public Name(string value)
{
Value = value;
}
public string Value { get; }
public override string ToString() => Value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment