There will often be a need to find not just one matching item in the DATABASE, (or to set the value of queried pattern variable for just one matching item) but to find all of them. For this purpose the looping construct FOREACH is provided, We can use it, for example to find all the items in the database in which "b" precedes "a":
[[a b c d] [d c b a] [a b d c] [b d c a]] -> database; foreach [== b == a ==] do it => endforeach;** [d c b a] ** [b d c a]
Note that FOREACH is a "syntax" word (like IF and DEFINE), not a procedure name, and hence the pattern specification that follows need not be enclosed in round brackets `(` `)'.
The general form of FOREACH is
FOREACH <pattern> DO <action> ENDFOREACH;For example, to print out every item in the database representing something blue:
vars x; foreach [??x is blue] do x ==> endforeach;Inside the <action> the variable IT is available to represent the database item which has matched the pattern. E.g. suppose you have various database entries of forms:
[p1 is a person] [b3 is a block] [c5 is a cat]etc. Then, to print out all the blocks do:
foreach [??x isa block] do x => endforeach;you can use "[%" and "%]" to make a list of all the blocks:
[% foreach [??x isa block] do x endforeach %] -> blocks;Each time round the value of X is left on the stack and the [%...%] brackets make a list of all of them. The variable IT can be used each time round the loop to refer to the database entry which was found to match the pattern given after FOREACH.
FOREACH can be followed by IN to specify a list other than DATABASE to search in, i.e.
FOREACH <pattern> IN <list> DO <action> ENDFOREACH;If you have access to a working Poplog system you can get more information and examples in:
TEACH MATCHES; TEACH DATABASE; TEACH FOREACH; TEACH RIVER2;