Forum > General

How to get rid of the recursion?

(1/1)

CandyMan30:
How to get rid of the recursion in the example below?
I could use a list, but how?

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---procedure tOptomizer.DoExpression( var CodeTree: pCodeTree);  begin    if Assigned( CodeTree) then      begin        DoExpression( CodeTree^.Left);        DoExpression( CodeTree^.Right);        case CodeTree^.Node.CodeType of...

MarkMLl:
Excessive fondness of recursion is something that often falls into my "Computer Science Crap" category. However unless you have very specific runtime requirements I suggest sticking with what you've got in the current scenario... albeit with careful depth etc. checking if you suspect that you'll be up against resource limitations.

In any event, you will need to consider whether an attempted conversion to an operations list does actually reduce the resource usage: recursion in a language with support for it can end up being very efficient.

MarkMLl

PascalDragon:

--- Quote from: CandyMan30 on December 08, 2022, 07:27:10 pm ---How to get rid of the recursion in the example below?
I could use a list, but how?

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---procedure tOptomizer.DoExpression( var CodeTree: pCodeTree);  begin    if Assigned( CodeTree) then      begin        DoExpression( CodeTree^.Left);        DoExpression( CodeTree^.Right);        case CodeTree^.Node.CodeType of...
--- End quote ---

What you're doing here is a depth-first search of a node tree. So you can do this with a loop and a stack (check the pseudo code in the linked article) though you might need to be careful when you do indeed change the CodeTree variable as the var suggests.

Navigation

[0] Message Index

Go to full version