Skip to content

Instantly share code, notes, and snippets.

@dezfowler
Created April 13, 2010 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dezfowler/364646 to your computer and use it in GitHub Desktop.
Save dezfowler/364646 to your computer and use it in GitHub Desktop.
Attempt at some currying with C#
using System;
using System.Collections.Generic;
public class MyClass
{
public static void RunSnippet()
{
// http://blog.robustsoftware.co.uk/2010/04/currying-with-c.html
// http://gist.github.com/360105
Func<int, int> addFive = i => i + 5;
Func<int, int> square = i => i * i;
Func<int, int, int> multiply = (i, j) => i * j;
Func<int, int> timesFive = multiply.Curry(5);
Random r = new Random();
Func<int> rand = () => r.Next(1, 10);
WL("Ten times five: {0}", timesFive(10));
WL("Random time five: {0}", timesFive((Curryable<int>)rand));
Curryable<int> sixteen = square.Curry(4);
WL("Four squared: {0}", sixteen);
Curryable<int> eightyOne = square.Curry(addFive(4));
WL("Four plus five, squared: {0}", eightyOne);
Func<int, int> addFiveThenSquare = square.Curry(addFive);
WL("Ten plus five, squared: {0}", addFiveThenSquare(10));
Curryable<int> a = 5;
Curryable<int> b = (Func<int>)(() => 10);
WL("Five plus ten: {0}", a + b);
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
public class Curryable<T>
{
private T _val;
private Curryable(T t)
{
_val = t;
}
public static implicit operator Curryable<T>(T t)
{
return new Curryable<T>(t);
}
public static implicit operator Curryable<T>(Func<T> func)
{
return new Curryable<T>(func());
}
public static implicit operator T(Curryable<T> c)
{
return c._val;
}
public static implicit operator Func<T>(Curryable<T> c)
{
return () => c._val;
}
public override string ToString()
{
return _val.ToString();
}
}
public static class Currying
{
public static Func<TR> Curry<T1, TR>(this Func<T1, TR> func, T1 t1)
{
return () => func(t1);
}
public static Func<T1, T1> Curry<T1>(this Func<T1, T1> func, Func<T1, T1> func2)
{
return (t1) => func(func2(t1));
}
public static Func<T1, TR> Curry<T1, TR>(this Func<T1, T1, TR> func, T1 t1)
{
return (t2) => func(t1, t2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment