Re: Dynamic foreach algorithm



Responding to Veloz...

How would you design a solution for the problem of effectively needing
a number of nested "foreach" statements but you don't know the number
at compile that?

That is let's say your algorithm needs to produce combinations. If you
knew in advance you had two "levels" of things, you would write

foreach(level1 = 0; level1 < somecount; level++) {
foreach(level2 = 0; level2 < somecount2; level2++) {
// do something with level1 and level2
}
}

If you knew in advance that you three such levels you would do this

foreach(level1 = 0; level1 < somecount; level++) {
foreach(level2 = 0; level2 < somecount2; level2++) {
foreach(level3 = 0; level3 < somecount3; level3++) {
// do something using level1, level2, level3
}
}
}

First note that the bodies of these two examples are necessarily different because they are parameterized differently (i.e., the second example needs level3 but the first does not). So, in effect, you are solving two different problems.

However, there are problems where data is optional or can be defaulted. In that case, the number of variables being modified could change. The answer in those kinds of problems is to separate the computational body from the iterations. So one might have something like:

[ParameterList]
+ level1
+ level2
+ level3
....
+ setNextIteration()
| 1
| accesses
|
| R2
|
| 1
[Body]
+ doIt()

On each iteration somebody invokes setNextIteration() and then doIt(). The setNextIteration incorporates whatever iteration is necessary and keeps track of where it is. (It needs some sort of reset() as well.) The [ParameterList] keeps track of /all/ the possible parameters, some of which may be defaulted or designated IGNORE. The doIt() behavior accesses the levelN values and plugs them into its internal computation.

Note that the doIt computation is independent of how many levels of iteration there are so long as it is viable to use defaults or ignore values that aren't provided.

Now it is possible to parameterize the iteration. The setNextIteration() behavior just needs to know which levelN values can be incremented, which can be handled by a bitmap. It then just "walks" the increment through the list of levels whose values change. As Daniel T. points out, that reduces the problem to more of a language manipulation issue.


--
There is nothing wrong with me that could
not be cured by a capful of Drano.

H. S. Lahman
hsl@xxxxxxxxxxxxxxxxx
Pathfinder Solutions
http://www.pathfindermda.com
blog: http://pathfinderpeople.blogs.com/hslahman
"Model-Based Translation: The Next Step in Agile Development". Email
info@xxxxxxxxxxxxxxxxx for your copy.
Pathfinder is hiring: http://www.pathfindermda.com/about_us/careers_pos3.php.
(888)OOA-PATH
.