Skip to content

Instantly share code, notes, and snippets.

@kakkun61
Created July 8, 2012 14:53
Show Gist options
  • Save kakkun61/3071262 to your computer and use it in GitHub Desktop.
Save kakkun61/3071262 to your computer and use it in GitHub Desktop.
Functional Composition in C# ver. 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FunctionalComposition
{
class FunctionalComposition
{
static void Main(string[] args)
{
var f = new Function<double, double>(Math.Exp);
var g = new Function<double, double>(x => Math.Pow(x, 2));
var h = new Function<double, double>(x => -x + 1);
var composed = f.Compose(g).Compose(h);
Console.WriteLine(composed.apply(10));
}
}
class Function<T, TResult>
{
public Func<T, TResult> apply
{
get;
protected set;
}
public Function(Func<T, TResult> apply)
{
this.apply = apply;
}
public Function<U, TResult> Compose<U>(Function<U, T> g)
{
return new Function<U, TResult>(x => apply(g.apply(x)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment