Iterating with foreach

foreach with Slot Names


foreach slotname,value in frame do statement

foreach slotname,value in frame collect statement


In some cases, you may want to iterate over each slot's name (actually, the symbol) as well as its value. Nicely enough, an alternative form of the foreach loop provides this capability. This version takes two loop variables rather than one. For each iteration, the first variable takes on the slot name (the symbol of the slot), while the second takes on the slot value. Here is a frame:

x := {a: 3, b: 9, c: 15);
with this variation of foreach:

foreach slotname,value in x do
   Print(slotname && value);
This will print out:

"a 3"
"b 9"
"c 15"
Here is another example of using foreach. It is a rather slow way of copying the slots from one frame to another (see "Clone/DeepClone" on page 60 for a quicker way). First, here are the frames:

x := {a: 3, b: 9, c: 15};
y := {};
Now, using foreach, here is the actual copying:

foreach symbol, frameValue in x do
   y.(symbol) := frameValue;
This foreach with two loop variables also works with arrays; the first variable takes on the index number, while the second takes on the value at that index. For instance, here is a way to pretty-print an array:

x := [3, 9, 15, "c"];
foreach indexValue, e in x do begin
   Write(indexValue);
   Write(": ");
   Print(e);
end;
When you execute this, it prints:

0: 3
1: 9
2: 15
3: "c"
There are also versions of foreach that work up the inheritance chain. For information on them, see "The deeply Version of foreach" on page 93.


An online version of Programming for the Newton using Macintosh, 2nd ed. ©1996, 1994, Julie McKeehan and Neil Rhodes.

Last modified: 1 DEC 1996