Skip to content

Instantly share code, notes, and snippets.

@PatrickMcDonald
Last active August 29, 2015 14:05
Show Gist options
  • Save PatrickMcDonald/1f7432d4d5c5ede45946 to your computer and use it in GitHub Desktop.
Save PatrickMcDonald/1f7432d4d5c5ede45946 to your computer and use it in GitHub Desktop.
namespace Curry
{
using System;
internal static class Program
{
// Curry methods
public static TResult Curry<T, TResult>(this Func<T, TResult> f, T arg)
{
// Curry'2 is just invoke
return f.Invoke(arg);
}
public static Func<T2, TResult> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> f, T1 arg1)
{
return arg2 => f.Invoke(arg1, arg2);
}
public static Func<T2, T3, TResult> Curry<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> f, T1 arg1)
{
return (arg2, arg3) => f.Invoke(arg1, arg2, arg3);
}
// Test Methods
public static int Square(int x)
{
return x * x;
}
public static int Add(int x, int y)
{
return x + y;
}
public static int Sum(int x, int y, int z)
{
return x + y + z;
}
public static double Pown(double @base, int exponent)
{
if (exponent < 0)
{
throw new ArgumentException("Exponent cannot be negative", "exponent");
}
double result = 1;
for (int i = 0; i < exponent; i++)
{
result *= @base;
}
return result;
}
// Program entry point
internal static void Main(string[] args)
{
Console.WriteLine("Square 2 = {0}", Curry(Square, 2));
// Call Curry with named function
var add1 = Curry<int, int, int>(Add, 1);
Console.WriteLine("add1 3 = {0}", add1.Invoke(3));
// Call curry with Func object
Func<int, int, int> add = Add;
var add2 = add.Curry(2);
Console.WriteLine("add2 4 = {0}", add2.Invoke(4));
// Call curry with lambda
Func<int, int, int> addLambda = (x, y) => x + y;
var add3 = addLambda.Curry(3);
Console.WriteLine("add3 5 = {0}", add3.Invoke(5));
// Call curry with differing parameter types
Func<double, int, double> pown = Pown;
var threeToThe = pown.Curry(3.0);
Console.WriteLine("threeToThe 2 = {0}", threeToThe(2));
// Curry'4
Func<int, int, int, int> sum = Sum;
var add4 = sum.Curry(1).Curry(3);
Console.WriteLine("add4 6 = {0}", add4(6));
Console.WriteLine("add5 7 = {0}", sum.Curry(2).Curry(3).Curry(7));
Console.WriteLine();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment