Code
Diff
  • namespace Currying {
      using System;
    
      public static class Functions {
        public static Func<TOut1> Curry<TOut1>(this Func<TOut1> fn) => () => fn();
        public static Func<TIn1, TOut2> Curry<TIn1, TOut2>(this Func<TIn1, TOut2> fn) => a => fn(a);
        public static Func<TIn1, Func<TIn2, TOut3>> Curry<TIn1, TIn2, TOut3>(this Func<TIn1, TIn2, TOut3> fn) => a => b => fn(a, b);
        public static Func<TIn1, Func<TIn2, Func<TIn3, TOut4>>> Curry<TIn1, TIn2, TIn3, TOut4>(this Func<TIn1, TIn2, TIn3, TOut4> fn) => a => b => c => fn(a, b, c);
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, TOut5>>>> Curry<TIn1, TIn2, TIn3, TIn4, TOut5>(this Func<TIn1, TIn2, TIn3, TIn4, TOut5> fn) => a => b => c => d => fn(a, b, c, d);
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, Func<TIn5, TOut6>>>>> Curry<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6>(this Func<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6> fn) => a => b => c => d => e => fn(a, b, c, d, e);
      }
    }
  • 1
    var test = new Currying.TestCurrying();
    
    2
    test.testSequential();
    
    3
    test.testRandom();
    
    1+
    namespace Currying {
    
    2+
      using System;
    
    3+
    4+
      public static class Functions {
    
    5+
        public static Func<TOut1> Curry<TOut1>(this Func<TOut1> fn) => () => fn();
    
    6+
        public static Func<TIn1, TOut2> Curry<TIn1, TOut2>(this Func<TIn1, TOut2> fn) => a => fn(a);
    
    7+
        public static Func<TIn1, Func<TIn2, TOut3>> Curry<TIn1, TIn2, TOut3>(this Func<TIn1, TIn2, TOut3> fn) => a => b => fn(a, b);
    
    8+
        public static Func<TIn1, Func<TIn2, Func<TIn3, TOut4>>> Curry<TIn1, TIn2, TIn3, TOut4>(this Func<TIn1, TIn2, TIn3, TOut4> fn) => a => b => c => fn(a, b, c);
    
    9+
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, TOut5>>>> Curry<TIn1, TIn2, TIn3, TIn4, TOut5>(this Func<TIn1, TIn2, TIn3, TIn4, TOut5> fn) => a => b => c => d => fn(a, b, c, d);
    
    10+
        public static Func<TIn1, Func<TIn2, Func<TIn3, Func<TIn4, Func<TIn5, TOut6>>>>> Curry<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6>(this Func<TIn1, TIn2, TIn3, TIn4, TIn5, TOut6> fn) => a => b => c => d => e => fn(a, b, c, d, e);
    
    11+
      }
    
    12+
    }
    

I've written a Curry class Add that can be used as follows.

var c = new Curry();
c.Add(1)(1); //should make c.Number == 2.
c.Add(3)(4)(5); //should make c.Number == 12.

Are there other ways of doing this same kind of thing in c#? I would love to see what you can come up with. My version of the Curry class has been added in the Preloaded section.

I've also included the TestCurrying class for us to test that the behavior is as expected. I am not sure how to setup proper tests with c#, so hopefully this gives us something we can run with.

var test = new Currying.TestCurrying();
test.testSequential();
test.testRandom();