Recursion + global/referenced/object/array variables
Posted on October 1, 2019
Tags: induction
- recursion in non-pure language is confusing because some variables are assigned by reference, particularly arrays.
- In recursion with global/referenced/object variables, the recursively spawned child process can manipulate the global/referenced/object variable of the parent process.
A visual python version is python recursion with global/referenced/object variables
In the example below the recursively spawned process manipulated the
//When fusing recursion with a global object
//the recursively spawned child can modify the parent's variable's state
//in this case the parent's tokens got modified
//tokens in many way acts like a global variable
function mktree(tokens){
// let tokens = [...tokens1] //if you uncomment this recursion breaks because tokens is a pure array
let partialSol = []
let head = tokens.shift() //THIS pops off the tokens of the original parent process
if(head == '('){
while(tokens[0] != ')'){
console.log(tokens)
let IH = mktree(tokens)
.push(IH)
partialSol
}return partialSol
else{
}// console.log(rest)
return head
}
}
//When fusing recursion with a global object
//the recursively spawned child can modify the parent's variable's state
//in this case the parent's tokens got modified
//tokens in many way acts like a global variable
function mktree(tokens){
let tokens = [...tokens1] //emulate a pure tokens that has no reference to the parent tokens
let partialSol = []
let head = tokens.shift() //THIS pops off the tokens of the current process
if(head == '('){
while(tokens[0] != ')'){ //There will be an inifinite recursion here
console.log(tokens)
let IH = mktree(tokens)
.push(IH)
partialSol
}return partialSol
else{
}// console.log(rest)
return head
}
}