Iterators: Difference between revisions

Content added Content deleted
(Added XPL0 example.)
Line 355: Line 355:
Saturday Wednesday Tuesday
Saturday Wednesday Tuesday
Purple Yellow Orange
Purple Yellow Orange
</pre>

=={{header|XPL0}}==
{{trans|C++}}
XPL0 doesn't have iterators as intended here. It has no built-in linked
lists, thus an array is used instead. This translation is about as close
as XPL0 can come to meeting the requirements of the task.

<lang XPL0>
\\ Use iterators to print all of the elements of any container that supports
\\ iterators. It print elements starting at 'start' up to, but not
\\ including, 'sentinel'.
proc PrintContainer(Start, Sentinel);
int Start, Sentinel, It;
[It:= 0;
while Start(It) # Sentinel do
[Text(0, Start(It)); Text(0, " ");
It:= It+1;
];
Text(0, "^m^j");
];
\\ Use an iterator to print the first, fourth, and fifth elements
proc FirstFourthFifth(Start, Dir);
int Start, Dir, It;
[It:= 0;
Text(0, Start(It));
It:= It + 3*Dir;
Text(0, ", "); Text(0, Start(It));
It:= It + 1*Dir;
Text(0, ", "); Text(0, Start(It));
Text(0, "^m^j");
];

\\ Create two different kinds of containers of strings
int Days, Colors;
[Days:= ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", 0];
Colors:= ["Red", "Orange", "Yellow", "Green", "Blue", "Purple", 0];
Text(0, "All elements:^m^j");
PrintContainer(Days, 0);
PrintContainer(Colors, 0);
Text(0, "^m^jFirst, fourth, and fifth elements:^m^j");
FirstFourthFifth(Days, +1);
FirstFourthFifth(Colors, +1);
Text(0, "^m^jReverse first, fourth, and fifth elements:^m^j");
FirstFourthFifth(@Days(7-1), -1);
FirstFourthFifth(@Colors(6-1), -1);
]</lang>

{{out}}
<pre>
All elements:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Red Orange Yellow Green Blue Purple

First, fourth, and fifth elements:
Sunday, Wednesday, Thursday
Red, Green, Blue

Reverse first, fourth, and fifth elements:
Saturday, Wednesday, Tuesday
Purple, Yellow, Orange
</pre>
</pre>