Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expressions c#

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

like image 501
finder_sl Avatar asked Mar 28 '26 01:03

finder_sl


1 Answers

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.

like image 85
leppie Avatar answered Mar 29 '26 13:03

leppie