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
lambda expressions c#
712 Views Asked by finder_sl At
3
There are 3 best solutions below
0

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

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.
Generic version:
Due to C#'s lack of proper lexical scoping, we need a whole bunch of temporary variables with different names.