compiler construction - How and where are the interim results in a recursion stored? -
i trying understand how recursion works in terms of interpreter. therefore, implemented simple recursion function in r:
> fac <- function(x) { + print(x) + if(x==0) return(1) + else {x*fac(x-1)} + } > > fac(4) [1] 4 [1] 3 [1] 2 [1] 1 [1] 0 [1] 24 > i understand recursion not how interpreter stores interim results. in example start fac(4) returns 4*fac(3) 3*fac(2) , on. or how such interim results stored? once function final call 1*fac(0) still needs sum results previous calls. again, these must stored or kept in memory beforehand. hope it's understandable trying ask. not sure how explain properly...
the state of every call stays in stack. generations have own version of x , every except base case multiplication after lower recursions finished. called continuation making recursive function not possible tail call optimize. multiplication happens on unrolling side after base case hit.
strange language if have return in base case not return x*fac(x-1). seems inconsistent.
Comments
Post a Comment