ruby - Recursion and order of statements execution -
this question deals how statements , involving recursion executed, , in order ruby handle the,. specifically, i've been learning online, have found ruby not follow last in first out convention in stack form of memory-management, rather has garbage collector. have numbered questions @ bottom after code. hope have made clear, please let me know parts of question may need improvement. thank you.
def append(array, n) return array if n < 0 #base case, how end thing array << n*2 #line no. 1 append(array, n - 1) #line no. 2 array << n*2 #line no. 3 end append( [], 3) #output [6,4,2,0,0,2,4,6]
the 2 lines below give output of [6,4,2,0]
array << n*2 #line no. 1 append(array, n - 1) #line no. 2
when order of 2 statements reversed output [0,2,4,6]
append(array, n - 1) #line no. 2 array << n*2 #line no. 3
- in original append method (top section of code), why ruby stop compute @ first recursive call, continue on line 3, , second recursive call, concatenate output of both recursions?
- if line 2 , line 3 part of recursion output be
[0,2,4,6]
, in ascending order. convention ruby uses in execution? why code not give output[6,4,2,0]
, sincen-1
being called beforearray << n*2
? - is there proper definition or programming theory how these recursive calls handled?
ruby doing nothing unusual here, more other "typical" computer language.
in original append method (top section of code), why ruby stop compute @ first recursive call, continue on line 3, , second recursive call, concatenate output of both recursions?
i don't see evidence this. first half of output 6,4,2,0
line 1. second half 0,2,4,6
line 3. note first time falls through line 3 when n==0
. next value after 6,4,2,0
0
, 2
, 4
, , 6
. pops out of call stack, lifo, other computer language.
if line 2 , line 3 part of recursion output be[0,2,4,6], in ascending order. convention ruby uses in execution? why code not give output [6,4,2,0], since n-1 being called before array << n*2?
because has call append
4 times before returns fall through line 3. time, n=0
why 0
still first in case.
is there proper definition or programming theory how these recursive calls handled?
it's lifo. give more thought.
if you're still not convinced, here c++ code prints exact same sequence:
#include <iostream> #include <list> using namespace std; list<int>& append( list<int> &array, int n ) { if( n < 0 ) return array; array.push_back(n*2); append( array, n-1 ); array.push_back(n*2); return array; } int main() { list<int> array; append( array, 3 ); for( int& x : array ) cout << x << ' '; cout << endl; }
Comments
Post a Comment