lambda expressions c#

712 Views Asked by At

I would like to know how to make function composition using lambda expression. I mean, I have 2 function f(x) and g(x). How to make their composition f(g(x)) using lambda expressions? Thanks

3

There are 3 best solutions below

2
On BEST ANSWER

Generic version:

static Func<T, T> Compose<T>(params Func<T, T>[] ff)
{
  Func<T, T> id = x => x;

  foreach (var f in ff)
  {
    var i = f;
    var idd = id;
    id = x => i(idd(x));
  }

  return id;
}

Due to C#'s lack of proper lexical scoping, we need a whole bunch of temporary variables with different names.

0
On
Func<int, int> f = x => x + 1;
Func<int, int> g = x => x * 2;
Func<int, int> fg = x => f(g(x));

Console.WriteLine(fg(5));
0
On

Your question is very brief, I am not sure if I get it well, however I think this is what you need:

Func<int,int> compose(Func<int,int> f, Func<int,int> g)
{
    return x=>f(g(x));
}

var fg = compose(f,g);

Func<int,int> f = ....
Func<int,int> g = ....
Func<int,int> fg = compose(f,g);

The problem with C# is that you need to write such compose functions for each different method signatures and therefore you could not compose functions using a generic method.