Iterators: Difference between revisions

15,832 bytes added ,  5 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
(A Python implementation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(9 intermediate revisions by 7 users not shown)
Line 16:
If you language supports iterators, use them. Otherwise show how access to elements can be
separated from the containers that hold them.
=={{header|68000 Assembly}}==
The easiest way to do this is with a table of pointers, as they're always 4 bytes regardless of the size of the data they point to.
 
Also, I'm making the assumption that the "Print the first, fourth, and fifth elements of each container" were intended to be one-indexed (i.e print the strings at offsets zero, three, and four)
<syntaxhighlight lang="68000devpac">main:
 
PrintAll:
MOVE.W #7-1,D7
MOVEQ #0,D1
.loop:
LEA Days_Of_The_Week,A0
LEA Colors,A1
MOVE.W D1,D2
LSL.W #2,D2
MOVEA.L (A0,D2),A3
JSR PrintString ;unimplemented hardware-dependent printing routine
MOVEA.L (A1,D2),A3
JSR PrintString
ADDQ.W #1,D1
DBRA D7,.loop
 
Part2:
LEA Days_Of_The_Week,A0
LEA Colors,A1
MOVEA.L (A0),A3
JSR PrintString
MOVEA.L (12,A0),A3
JSR PrintString
MOVEA.L (16,A0),A3
JSR PrintString
MOVEA.L (A1),A3
JSR PrintString
MOVEA.L (12,A1),A3
JSR PrintString
MOVEA.L (16,A1),A3
JSR PrintString
 
Part3:
LEA Days_Of_The_Week,A0
LEA Colors,A1
MOVEA.L (24,A0),A3
JSR PrintString
MOVEA.L (12,A0),A3
JSR PrintString
MOVEA.L (8,A0),A3
JSR PrintString
MOVEA.L (20,A1),A3
JSR PrintString
MOVEA.L (8,A1),A3
JSR PrintString
MOVEA.L (4,A1),A3
JSR PrintString
 
JMP * ;HALT THE CPU
 
Days_Of_The_Week:
DC.L Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
; 0 4 8 12 16 20 24
 
Sunday:
DC.B "Sunday",0
EVEN ;conditionally aligns to a 2-byte boundary if the data isn't aligned already
Monday:
DC.B "Monday",0
EVEN
Tuesday:
DC.B "Tuesday",0
EVEN
Wednesday:
DC.B "Wednesday",0
EVEN
Thursday:
DC.B "Thursday",0
EVEN
Friday:
DC.B "Friday",0
EVEN
Saturday:
DC.B "Saturday",0
EVEN
 
Colors:
DC.L Red,Orange,Yellow,Green,Blue,Purple
 
Red:
DC.B "Red",0
even
Orange:
DC.B "Orange",0
even
Yellow:
DC.B "Yellow",0
even
Green:
dc.b "Green",0
even
Blue:
dc.b "Blue",0
even
Purple:
dc.b "Purple",0
even</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="AutoHotkey">oDays := ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
oColors := ["Red","Orange","Yellow","Green","Blue","Purple"]
MsgBox % Result := ""
. "All elements:`n" Iterators(oDays) "`n" Iterators(oColors)
. "`n`nFirst, fourth, and fifth:`n" Iterators(oDays, [1,4,5]) "`n" Iterators(oColors, [1,4,5])
. "`n`nReverse first, fourth, and fifth:`n" Iterators(oDays, [1,4,5], 1) "`n" Iterators(oColors, [1,4,5], 1)
return
 
Iterators(obj, num:="", rev:=0){
for i, v in (num.Count() ? num : obj)
res .= (rev ? obj[obj.Count() +1 -v] : num.Count() ? obj[v] : v) ", "
return Trim(res, ", ") "."
}</syntaxhighlight>
{{out}}
<pre>All elements:
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday.
Red, Orange, Yellow, Green, Blue, Purple.
 
First, fourth, and fifth:
Sunday, Wednesday, Thursday.
Red, Green, Blue.
 
Reverse first, fourth, and fifth:
Saturday, Wednesday, Tuesday.
Purple, Yellow, Orange.</pre>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">arraybase 1
dim list$ = {{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, {"Red","Orange","Yellow","Green","Blue","Purple"}}
dim ind = {1,4,5}
Line 51 ⟶ 180:
print
end
</syntaxhighlight>
</lang>
<pre>Igual que la entrada de FreeBASIC.</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <list>
#include <string>
Line 104 ⟶ 233:
FirstFourthFifth(colors.rbegin());
}
</syntaxhighlight>
</lang>
{{out}}
<pre>All elements:
Line 118 ⟶ 247:
Purple, Yellow, Orange
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Classes,StdCtrls,ExtCtrls}}
This uses a simiple iterator built from Delphi objects. Like all iterators, it hides the detail of how the collection of items is stored. The user can only access the data by called methods such as "Next" and "Previous." The object could be made generic so any type of collection object could be used to create a custom iterator.
 
<syntaxhighlight lang="Delphi">
{Simple iterator based around a string collection}
{The details of string storage are hidden from the user}
{Strings are only accessible through the supplied interface}
 
type TStringIterator = class(TObject)
private
Collection: TStringList;
Index: integer;
protected
public
constructor Create;
destructor Destroy; override;
procedure Add(S: string);
procedure Insert(const Item, Before: string);
procedure Remove(const Item: string);
procedure Clear;
function Contains(const Item: string): Boolean;
function GetCount: Integer;
procedure Reset;
function Next: Boolean;
function Previous: Boolean;
procedure Last;
function CurrentItem: string;
procedure LoadArray(SA: array of string);
end;
 
{ TStringIterator }
 
procedure TStringIterator.Add(S: string);
{Add item to Collection}
begin
Collection.Add(S);
end;
 
procedure TStringIterator.Clear;
{Clear collection}
begin
Collection.Clear;
end;
 
function TStringIterator.Contains(const Item: string): Boolean;
{Test if string is in collection}
begin
Result:=Collection.IndexOf(Item)>=0;
end;
 
constructor TStringIterator.Create;
{Create collection and initialize}
begin
Collection:=TStringList.Create;
Clear;
Reset;
end;
 
 
function TStringIterator.CurrentItem: string;
{Return current item from collection}
begin
Result:=Collection[Index];
end;
 
destructor TStringIterator.Destroy;
{Dispose of collection}
begin
Collection.Free;
inherited;
end;
 
 
function TStringIterator.GetCount: Integer;
{Return count of items in collection}
begin
Result:=Collection.Count;
end;
 
procedure TStringIterator.Insert(const Item, Before: string);
{Insert item in collection before specified item}
{If "Before" isn't found, insert at end of collection}
var Inx: integer;
begin
if Before='' then Collection.Add(Item)
else
begin
Inx:=Collection.IndexOf(Before);
if Inx>=0 then Collection.Insert(Inx,Item);
end
end;
 
function TStringIterator.Next: Boolean;
{Point to next item in collection}
{Return false if no more items in collection}
begin
Result:=(Index<Collection.Count-1);
if Result then Inc(Index);
end;
 
function TStringIterator.Previous: Boolean;
{Point to previous item in collection}
{Return false if no more Previous items in collection}
begin
Result:=(GetCount>0) and (Index>0);
if Result then Dec(Index);
end;
 
 
procedure TStringIterator.Remove(const Item: string);
{Remove specified item from list}
var Inx: integer;
begin
Inx:=Collection.IndexOf(Item);
if Inx>=0 then Collection.Delete(Inx);
end;
 
procedure TStringIterator.Reset;
{Point to start of collection}
begin
Index:=0;
end;
 
procedure TStringIterator.Last;
{Point to Last item in collection}
begin
Index:=Collection.Count-1;
end;
 
 
 
procedure TStringIterator.LoadArray(SA: array of string);
{Load array of strings into Collection}
var I: integer;
begin
for I:=0 to High(SA) do Add(SA[I]);
end;
 
 
{-----------------------------------------------------------}
 
 
procedure TestIterator(Memo: TMemo);
var WeekDays,Colors: TStringIterator;
 
function Traverse(Iter: TStringIterator): string;
begin
Iter.Reset;
Result:='';
repeat Result:=Result+Iter.CurrentItem+' ';
until not Iter.Next;
end;
 
function FirstFourthFifth(Iter: TStringIterator): string;
var I: integer;
begin
Iter.Reset;
Result:='';
Result:=Result+Iter.CurrentItem+' ';
for I:=1 to 3 do Iter.Next;
Result:=Result+Iter.CurrentItem+' ';
Iter.Next;
Result:=Result+Iter.CurrentItem+' ';
end;
 
function LastFourthFifth(Iter: TStringIterator): string;
var I: integer;
begin
Iter.Last;
Result:='';
Result:=Result+Iter.CurrentItem+' ';
for I:=1 to 3 do Iter.Previous;
Result:=Result+Iter.CurrentItem+' ';
Iter.Previous;
Result:=Result+Iter.CurrentItem+' ';
end;
 
begin
WeekDays:=TStringIterator.Create;
try
Colors:=TStringIterator.Create;
try
WeekDays.LoadArray(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']);
Colors.LoadArray(['Red','Orange','Yellow','Green','Blue','Purple']);
 
Memo.Lines.Add(Traverse(Weekdays));
Memo.Lines.Add(Traverse(Colors));
Memo.Lines.Add(FirstFourthFifth(Weekdays));
Memo.Lines.Add(FirstFourthFifth(Colors));
Memo.Lines.Add(LastFourthFifth(Weekdays));
Memo.Lines.Add(LastFourthFifth(Colors));
 
finally Colors.Free; end;
finally WeekDays.Free; end;
end;
 
</syntaxhighlight>
{{out}}
<pre>
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Red Orange Yellow Green Blue Purple
Sunday Wednesday Thursday
Red Green Blue
Saturday Wednesday Tuesday
Purple Yellow Orange
 
</pre>
 
 
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//Iterators. Nigel Galloway: Januuary 30th., 2022
let N,G=[|"Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday"|],["Red"; "Orange"; "Yellow"; "Green"; "Blue"; "Purple"]
Line 136 ⟶ 476:
let X=(N|>Array.rev|>Seq.ofArray).GetEnumerator() in printfn $"{next X} {(advance X 3; next X)} {next X}"
let X=(G|>List.rev|>Seq.ofList).GetEnumerator() in printfn $"{next X} {(advance X 3; next X)} {next X}"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 151 ⟶ 491:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Dim As Integer n, m
Dim As String list(1 To 2, 1 To 7) = {_
{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, _
Line 181 ⟶ 521:
Print list(2, Ubound(list,2)-ind(m)); " ";
Next m
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 193 ⟶ 533:
Still, one approach here might be:
 
<langsyntaxhighlight Jlang="j">dow=: ;:'monday tuesday wednesday thursday friday saturday sunday'
col=: (,<)/;:'red orange yellow green blue purple'</langsyntaxhighlight>
 
This gives us:
 
<syntaxhighlight lang="j">
<lang J>
dow
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐
Line 216 ⟶ 556:
│ ││ │└──────┴───────────────────────┘││
│ │└──────┴────────────────────────────────┘│
└───┴─────────────────────────────────────────┘</langsyntaxhighlight>
 
Here, the implementation's array indexing would see the linked list representation as a two element array. To index arbitrary elements from the linked list, we might map back from the linked list representation to a flat array representation, perhaps using <S:0 (which is a no-op on our array of days of week).
 
<langsyntaxhighlight Jlang="j"> echo ;:inv <S:0 dow
monday tuesday wednesday thursday friday saturday sunday
echo ;:inv <S:0 col
Line 233 ⟶ 573:
sunday friday thursday
echo ;:inv _1 _3 _4 {<S:0 col
purple green yellow</langsyntaxhighlight>
 
The downside of this approach is that the programmer must understand the data (to know to map all relevant list structures to the desired form). For example, we might instead say that a linked list is not merely an unbalanced binary tree, but must always have its data elements in the left node. That would give us this implementation for col:
 
<syntaxhighlight lang="j">
<lang J>
col=: '' ]F..(,<) ;:'red orange yellow green blue purple'
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight Jlang="j"> col
┌──────┬───────────────────────────────────────┐
│purple│┌────┬────────────────────────────────┐│
Line 254 ⟶ 594:
│ ││ │└─────┴────────────────────────┘││
│ │└────┴────────────────────────────────┘│
└──────┴───────────────────────────────────────┘</langsyntaxhighlight>
 
This creates an issue that a single element nested list looks very much like a flat array. To prevent that from being a problem, we include an empty element at the end of our flat array:
 
<syntaxhighlight lang="j">
<lang J>
dow=: a:,~;:'monday tuesday wednesday thursday friday saturday sunday'
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight Jlang="j"> dow
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┬┐
│monday│tuesday│wednesday│thursday│friday│saturday│sunday││
└──────┴───────┴─────────┴────────┴──────┴────────┴──────┴┘</langsyntaxhighlight>
 
Now everything is the same as before, except that we need to explicitly ignore the empty trailing element:
 
<langsyntaxhighlight Jlang="j"> echo ;:inv _2 _4 _5 {<S:0 dow
sunday friday thursday
echo ;:inv _2 _4 _5 {<S:0 col
red yellow green</langsyntaxhighlight>
 
That said, we now also have the opportunity to implement a different kind of normalization routine, which takes advantage of the difference in representation (if we had a need for that...).
Line 282 ⟶ 622:
For example:
 
<langsyntaxhighlight Jlang="j">nextItem=: {{ (x+1) -.#y }}
nextLink=: {{ (1;x) #~ (L.y) > #x }}
 
Line 297 ⟶ 637:
more=: {{'`next val more'=. ops['ops list position'=. y
more position
}}</langsyntaxhighlight>
 
With this approach, one of the task examples could look like this:
 
<syntaxhighlight lang="j">
<lang J>
printAll=: {{
while. more y do.
Line 329 ⟶ 669:
monday
value iterate^:3 DOW
thursday</langsyntaxhighlight> etc.
 
(Except that this approach does not support negative indexing, so indexing from the end of a list would, for the general case, require either extending the system with explicit support for a length operation or iterating once over the list to determine the list length.)
 
=={{header|jq}}==
'''Works with both jq and gojq, the C and Go implementations of jq'''
 
In this entry, singly-linked lists (SLL) are represented
by JSON objects of the form `{item, next}`, that is by
objects with two keys, where `.item` is an item in
the list, and `.next` is the next SLL.
 
Since jq does not have an iterator interface, and since jq's array iterator is not extensible,
this entry defines a collection of polymorphic functions that will accept arrays or SLLs
as input, and that will produce identical results for equivalent inputs.
To highlight these functions, they will be named by using the prefix "poly_".
 
In particular, the function `poly_task` illustrates how all the
specified tasks for this page can be defined without reference to the input type,
with the results being the
same for equivalent inputs.
<syntaxhighlight lang=jq>
# Generic utilities
def count(s): reduce s as $x (0; .+1);
 
# A constructor for SLL:
def new($item): {$item, next: null};
 
# Append a single item to an array or SLL.
# If the input is {} or a SLL, the output is a SLL
# If the input is null or an array, the output is an array
def append($item):
def a: if .next then .next |= a else .next=new($item) end;
if . == null then [$item]
elif . == {} then new($item)
else a
end;
 
# Append a stream of items using `append/1`
def append_items(stream):
reduce stream as $item (.; append($item));
 
# Produce a stream of items
def poly_items:
if type == "array" then .[]
else .item, (select(.next).next|poly_items)
end;
 
def poly_length:
if type == "array" then length
else count(poly_items)
end;
 
# Output: the stream of items in reversed order
def poly_reversed:
if type == "array" then .[range(length-1; -1; -1)]
else [poly_items] | reverse[]
end;
 
# Two representations of Days of the Week (dow) and of colors:
def dow: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
def sll_dow: {} | append_items(dow[]);
 
def colors: [ "red", "orange", "yellow", "green", "blue", "indigo", "violet"];
def sll_colors: {} | append_items(colors[]);
 
def poly_task:
poly_length as $length
| "All the elements:", poly_items,
"",
"The first, fourth, and fifth elements:",
((0, 3, 4) as $i
| "For i=\($i): \(nth($i; poly_items))" ),
"",
"The last, fourth to last, and fifth to last elements:",
((0, 3, 4) as $i
| "For i=\($i): \(nth($i; poly_reversed) )" );
 
 
"For days of the week:",
"For arrays:", (dow | poly_task),
"",
"For singly-linked lists:", (sll_dow | poly_task),
"\n",
"For colors:",
"For arrays:", (colors | poly_task),
"",
"For singly-linked lists:", (sll_colors | poly_task)
</syntaxhighlight>
{{output}}
<pre style="height:20lh;overflow:auto>
For days of the week:
For arrays:
All the elements:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
 
The first, fourth, and fifth elements:
For i=0: Monday
For i=3: Thursday
For i=4: Friday
 
The last, fourth to last, and fifth to last elements:
For i=0: Sunday
For i=3: Thursday
For i=4: Wednesday
 
For singly-linked lists:
All the elements:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
 
The first, fourth, and fifth elements:
For i=0: Monday
For i=3: Thursday
For i=4: Friday
 
The last, fourth to last, and fifth to last elements:
For i=0: Sunday
For i=3: Thursday
For i=4: Wednesday
 
 
For colors:
For arrays:
All the elements:
red
orange
yellow
green
blue
indigo
violet
 
The first, fourth, and fifth elements:
For i=0: red
For i=3: green
For i=4: blue
 
The last, fourth to last, and fifth to last elements:
For i=0: violet
For i=3: green
For i=4: yellow
 
For singly-linked lists:
All the elements:
red
orange
yellow
green
blue
indigo
violet
 
The first, fourth, and fifth elements:
For i=0: red
For i=3: green
For i=4: blue
 
The last, fourth to last, and fifth to last elements:
For i=0: violet
For i=3: green
For i=4: yellow
</pre>
 
 
=={{header|Julia}}==
Line 341 ⟶ 853:
extensive set of functions which act on lists and vectors. Julia's Iterators can implement
the C++ example:
<langsyntaxhighlight lang="julia">using DataStructures
 
function PrintContainer(iterator)
Line 371 ⟶ 883:
FirstFourthFifth(reverse(days))
FirstFourthFifth(reverse(colors))
</langsyntaxhighlight>{{out}}
<pre>
All elements:
Line 384 ⟶ 896:
Saturday, Wednesday, Tuesday
Purple, Yellow, Orange
</pre>
 
=={{header|Nim}}==
Nim defines iterators for collection types such as arrays, sequences, sets, tables, etc. But it allows also to define our own iterators. There exists two kinds of such iterators: inline iterators (the current default) and closure iterators. Inline iterators are expanded, closure iterators are not.
 
In our solution, we use standard iterators and our own iterators.
<syntaxhighlight lang="Nim">import std/lists
 
# Days stored in an array.
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
 
# Colors stored in a doubly linked list.
let colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"].toDoublyLinkedList
 
 
### To print the elements of "days", we use a standard iterator.
echo "Content of “days” array:"
for day in days:
echo day
echo()
 
 
### To print the elements of "colors", we use a standard iterator.
echo "Content of “colors” list:"
for color in colors:
echo color
echo()
 
 
### To print the first, fourth an fifth elements
### of "days", we use a standard iterator.
echo "First, fourth and fifth elements of “days”:"
for i, day in days:
if i + 1 in [1, 4, 5]:
echo day
echo()
 
 
### To print the first, fourth an fifth elements
### of "colors", we must define our own iterator.
 
iterator enumerate[T](list: DoublyLinkedList[T]): (int, T) =
## Yield the successive (index, value).*
## First index is 0.
var i = 0
var node = list.head
while node != nil:
yield (i, node.value)
node = node.next
inc i
 
echo "First, fourth and fifth elements of “colors”:"
for i, color in colors.enumerate:
if i + 1 in [1, 4, 5]:
echo color
echo()
 
 
### To print the last, fourth to last, and fifth to last
### elements of "days", we must define our own iterator.
 
iterator revItems[T](a: openArray[T]): (int, T) =
## Starting from end of array, yield (index, value).
## First index is 1.
for i in countdown(a.high, 0):
yield (a.len - i, a[i])
 
echo "Last, fourth to last and fifth to last elements of “days”:"
for i, day in days.revItems:
if i in [1, 4, 5]:
echo day
echo()
 
 
### To print the last, fourth to last, and fifth to last
### elements of "colors", we must define our own iterator.
 
iterator revItems[T](list: DoublyLinkedList[T]): (int, T) =
## Starting from end of the list, yield (index, value).
## First index is 1.
var i = 1
var node = list.tail
while node != nil:
yield (i, node.value)
node = node.prev
inc i
 
echo "Last, fourth to last and fifth to last elements of “colors”:"
for i, color in colors.revItems:
if i in [1, 4, 5]:
echo color
</syntaxhighlight>
 
{{out}}
<pre>Content of “days” array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
 
Content of “colors” list:
Red
Orange
Yellow
Green
Blue
Purple
 
First, fourth and fifth elements of “days”:
Sunday
Wednesday
Thursday
 
First, fourth and fifth elements of “colors”:
Red
Green
Blue
 
Last, fourth to last and fifth to last elements of “days”:
Saturday
Wednesday
Tuesday
 
Last, fourth to last and fifth to last elements of “colors”:
Purple
Yellow
Orange
</pre>
 
Line 390 ⟶ 1,032:
five builtin data types it is not an issue for a routine to "know" what it is doing.<br>
Something along the lines of [[Same_fringe#Phix]] could perhaps also be used to implement custom iterators.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">print_all</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 420 ⟶ 1,062:
<span style="color: #000000;">printFirstFourthFifth</span><span style="color: #0000FF;">(</span><span style="color: #000000;">days</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">printFirstFourthFifth</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colors</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
Originally I used keys of 1..6 on the colours dictionary, but that looked suspicious.
Note that the keys here are a mix of int/flt/string/seq, but still carefully "in order".
Line 443 ⟶ 1,085:
We can create our own iterators by implementing the ''iterator protocol''. The iterator protocol requires us to implement an <code>__iter__</code> method and a <code>__next__</code> method, as demonstrated by the <code>MyIterable</code> and <code>MyIterator</code> classes below.
 
<langsyntaxhighlight lang="python">"""Iterables and iterators. Requires Python >= 3.6 for type hints."""
from collections import deque
from typing import Iterable
Line 564 ⟶ 1,206:
if __name__ == "__main__":
main()
</syntaxhighlight>
</lang>
 
{{out}}
Line 593 ⟶ 1,235:
The following example iterates though a hash of Positional Iterable objects and demonstrates both using explicit iterators, and object slice operations on each; then has a semi contrived example of where directly using iterators may be actually useful in Raku; collating unique ascending values from several infinite sequence generators.
 
<syntaxhighlight lang="raku" perl6line>my %positional-iterable-types =
array => [<Sunday Monday Tuesday Wednesday Thursday Friday Saturday>],
list => <Red Orange Yellow Green Blue Purple>,
Line 631 ⟶ 1,273:
}
 
say @seq[^25];</langsyntaxhighlight>
{{out}}
<pre>Note: here we are iterating over the %positional-iterable-types hash, but
Line 663 ⟶ 1,305:
=={{header|Ring}}==
{{incorrect|Ring|The task is specifically about ''iterators'', not [[wp:Iterator#Contrasting_with_indexing|counting loops with indexing]].}}
<langsyntaxhighlight lang="ring">
list = [["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
["Red","Orange","Yellow","Green","Blue","Purple"]]
Line 698 ⟶ 1,340:
 
see "done..." +nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 724 ⟶ 1,366:
 
The iterator protocol methods are not usually called directly as Wren's 'for' statement (and the Sequence methods) call them automatically under the hood. However, in the spirit of this task, they are called directly.
<langsyntaxhighlight ecmascriptlang="wren">import "./llist" for DLinkedList
 
// Use iterators to print all elements of the sequence.
Line 760 ⟶ 1,402:
System.print("\nReverse first, fourth, and fifth elements:")
printFirstFourthFifth.call(days[-1..0])
printFirstFourthFifth.call(colors.reversed)</langsyntaxhighlight>
 
{{out}}
Line 783 ⟶ 1,425:
as XPL0 can come to meeting the requirements of the task.
 
<syntaxhighlight lang="xpl0">
<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
Line 826 ⟶ 1,468:
FirstFourthFifth(@Days(7-1), -1);
FirstFourthFifth(@Colors(6-1), -1);
]</langsyntaxhighlight>
 
{{out}}
9,476

edits