FORNEST - Implementation of nested FOR loop

The format of the FORNEST function is:


The function returns a logical value after a loop has run to completion.
In normal programming terms, the operation of nested for loops may be visualised as follows:

 FOR a := 1 to 10 do   FORNEST({{a,1,10},{b,2,7}},Test@,...
  FOR b := 2 to 7 do
      c := a + b;      Test@ EQV LOGSTATE(c)

In a knowledge network, the individual FOR operators can be separate state machines, or they may be combined into a nested form, as here. There will be instances where the form of the statement being driven is

                    c := c + a + b

The FORNEST function may be used in conjunction with the LATCH or GETPUT functions, which will initialise and then retain the old value of a variable.
The parameters of the FORNEST Function are:

  List%  -Source of variables to be cycled, and values.
  Test@  -Returns value of test, "executes" loop.
  Move@  -Logical input, controls moving of values through GATE.
  Startup@ - Logical input, starts loop if TRUE, skip if FALSE.
  Initialise@ - Logical output, set TRUE on first cycle, then FALSE.

The values in the list can be of the following form

{{ a, 1, 5 }}
cycle a from 1 to 5 with default step of 1 or -1
{{ a, 8, 1, -2 }}
step is -2 - if step is given, sign is not changed
{ a, {2..5, X, 11<->13} }
cycle a through values in list, real range treated as one value
{{ a }, { b$ }, { i, 1, 1 }}
variables with distributions will be cycled through values in distribution - nesting of one variable to another works through relation - secondary variable (i) used to indicate completion of one cycle
{{ a, 1, 5 }, { b, a, 2*a}}
nested variables may depend on outer value
{ L@, {FALSE, TRUE} }
cycle logical variable through states
{ L1%, {L2%,L3%,L4%} }
cycle list variable through alternatives
The free variable A# will have its value set to B#, C#... in turn

Note the double bracing for simple loop indexes, necessary so loops can be nested.
In operation, searching comes in on link 1, the value of the function. What happens next is:

  1. Search for Startup@. If FALSE, return value
  2. Set Initialise@ to TRUE
  3. Go through list, setting variables to first value
  4. Search for Test@
  5. If Test@ is TRUE, search for Move@ else skip
  6. Set variable to next value, set Initialise@ to FALSE
  7. Go to step 4

The logic connected to the Test@ pin can be made to return FALSE or ERROR if an inconsistent result is found, so the FORNEST loop can be used to search for and save all valid values, or used to find a maximum by having part of the test be a check for higher than some previous value.
If a variable in the list of variables being set has a value already set, it will be trodden on.

Related Functions