Sunday, June 16, 2013

Function composition in C#

Inspired by the following JavaScript code snippet from : Compose functions as building blocks
var  roundedSqRoot = Math.round.compose(Math.sqrt);
roundedSqRoot(28); 

I was curious to figure out how to write this in C#. Considering that the input parameter type would be the same as the function output type, I came up with
public static Func<T1, T1> Compose1<T1>(params Func<T1, T1> [] functions)
{
    return new Func<T1, T1> ( (input) => {                
        T1 t1 = input;
        var l = functions.ToList();
        l.Reverse();
        foreach(var f in l) {
            t1 = f(t1);
        }
        return t1; 
    } );
}      

static void Main(string[] args)
{            
    var newF1 = Compose1<double>(Math.Round, Math.Sqrt);
    Console.WriteLine(newF1(28));
}

No comments:

Post a Comment