High Level Function Confusion with Lambda/LINQ expressions in C# -
unsure how describe question title might wrong.
am reading on code examples , confused on following return function:
func<func<int , bool>, func<int , int>, func<int , int>> loop = null ; loop = (c , f ) => n => c(n) ? loop(c , f ) ( f (n)): n; func<int , int> w = loop(n => n < 10 , n => n + 2); var r = w(2); var s = w(3); console . writeline ("{0} {1}" , r , s );
i understand function returning loop when c(n) evaluates true, don't understand how loop(c,f) (f(n)) evaluates - both being passed loop? have tried running dumps in linqpad , don't how bit running.
any appreciated, understand dumb question!
one way try understand start small: have basic loop 1-10 +1 increment.
func<int,int> basicloop = null; basicloop = n => n < 10 ? basicloop(n+1) : n;
that's pretty simple - basicloop
function based on parameter n
returns n
(for n >= 10) or calls incremented parameter. basicloop(8)
computed as:
basicloop(8)
8 < 10, callsbasicloop(8+1)
resultbasicloop(9)
9 < 10, callsbasicloop(9+1)
resultbasicloop(10)
10 == 10, returnsn
10.basicloop(9)
got result 10 (frombasicloop(10)
) , returns itbasicloop(8)
got result 10 (frombasicloop(9)
)and returns it
now want pass condition parameter loop. means our "loop" func
need pass condition around on every iteration:
type of condition (similar n<10
) - func<int, bool>
. have takes func<int,bool>
argument , returns same value our original basicloop
. hence func
of 1 argument , 1 result:
func<func<int, bool>, func<int,int>> condloop = null;
condloop
function of 1 argument - when defining take argument: condloop = (condition) => ...
.
we need replace condition in our original basicloop
: n => n < 10 ? ...
becomes n => condition(n) ? ...
.
the last part replacing basicloop(n+1)
- have condloop
function returns equivalent of basicloop
when pass condition it. fortunately our condition not change between iterations , have - condloop(condition)
equivalent of basicloop
. getting together:
condloop = (condition) => n => condition(n) ? condloop(condition) (n + 1) : n;
tracing through calls condloop(x => x < 5)(4)
condloop(x => x < 5)(4)
- conditionx => x < 5
, n = 4 whencondition(4)
called x = 4, 4 < 5 true - callingcondloop
same condition , increased n -condloop(x => x < 5)(4 + 1)
resultcondloop(x => x < 5)(5)
- conditionx => x < 5
, n = 5 whencondition(5)
called x = 5, 5 < 5 false - returningn
5- back
condloop(x => x < 5)(4)
- returning 5 result ofcondloop(x => x < 5)(5)
with similar logic adding function increments value - on every iteration need pass condition
, increment
function (c
, f
in original post).
Comments
Post a Comment