Iterators: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 20: | Line 20: | ||
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) |
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: |
PrintAll: |
||
Line 117: | Line 117: | ||
Purple: |
Purple: |
||
dc.b "Purple",0 |
dc.b "Purple",0 |
||
even</ |
even</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="freebasic">arraybase 1 |
||
dim list$ = {{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, {"Red","Orange","Yellow","Green","Blue","Purple"}} |
dim list$ = {{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, {"Red","Orange","Yellow","Green","Blue","Purple"}} |
||
dim ind = {1,4,5} |
dim ind = {1,4,5} |
||
Line 153: | Line 153: | ||
print |
print |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>Igual que la entrada de FreeBASIC.</pre> |
<pre>Igual que la entrada de FreeBASIC.</pre> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <list> |
#include <list> |
||
#include <string> |
#include <string> |
||
Line 206: | Line 206: | ||
FirstFourthFifth(colors.rbegin()); |
FirstFourthFifth(colors.rbegin()); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>All elements: |
<pre>All elements: |
||
Line 223: | Line 223: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
//Iterators. Nigel Galloway: Januuary 30th., 2022 |
//Iterators. Nigel Galloway: Januuary 30th., 2022 |
||
let N,G=[|"Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday"|],["Red"; "Orange"; "Yellow"; "Green"; "Blue"; "Purple"] |
let N,G=[|"Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday"|],["Red"; "Orange"; "Yellow"; "Green"; "Blue"; "Purple"] |
||
Line 238: | Line 238: | ||
let X=(N|>Array.rev|>Seq.ofArray).GetEnumerator() in printfn $"{next X} {(advance X 3; next X)} {next X}" |
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}" |
let X=(G|>List.rev|>Seq.ofList).GetEnumerator() in printfn $"{next X} {(advance X 3; next X)} {next X}" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 253: | Line 253: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">Dim As Integer n, m |
||
Dim As String list(1 To 2, 1 To 7) = {_ |
Dim As String list(1 To 2, 1 To 7) = {_ |
||
{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, _ |
{"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}, _ |
||
Line 283: | Line 283: | ||
Print list(2, Ubound(list,2)-ind(m)); " "; |
Print list(2, Ubound(list,2)-ind(m)); " "; |
||
Next m |
Next m |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 295: | Line 295: | ||
Still, one approach here might be: |
Still, one approach here might be: |
||
< |
<syntaxhighlight lang="j">dow=: ;:'monday tuesday wednesday thursday friday saturday sunday' |
||
col=: (,<)/;:'red orange yellow green blue purple'</ |
col=: (,<)/;:'red orange yellow green blue purple'</syntaxhighlight> |
||
This gives us: |
This gives us: |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
dow |
dow |
||
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐ |
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐ |
||
Line 318: | Line 318: | ||
│ ││ │└──────┴───────────────────────┘││ |
│ ││ │└──────┴───────────────────────┘││ |
||
│ │└──────┴────────────────────────────────┘│ |
│ │└──────┴────────────────────────────────┘│ |
||
└───┴─────────────────────────────────────────┘</ |
└───┴─────────────────────────────────────────┘</syntaxhighlight> |
||
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). |
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). |
||
< |
<syntaxhighlight lang="j"> echo ;:inv <S:0 dow |
||
monday tuesday wednesday thursday friday saturday sunday |
monday tuesday wednesday thursday friday saturday sunday |
||
echo ;:inv <S:0 col |
echo ;:inv <S:0 col |
||
Line 335: | Line 335: | ||
sunday friday thursday |
sunday friday thursday |
||
echo ;:inv _1 _3 _4 {<S:0 col |
echo ;:inv _1 _3 _4 {<S:0 col |
||
purple green yellow</ |
purple green yellow</syntaxhighlight> |
||
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: |
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' |
col=: '' ]F..(,<) ;:'red orange yellow green blue purple' |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="j"> col |
||
┌──────┬───────────────────────────────────────┐ |
┌──────┬───────────────────────────────────────┐ |
||
│purple│┌────┬────────────────────────────────┐│ |
│purple│┌────┬────────────────────────────────┐│ |
||
Line 356: | Line 356: | ||
│ ││ │└─────┴────────────────────────┘││ |
│ ││ │└─────┴────────────────────────┘││ |
||
│ │└────┴────────────────────────────────┘│ |
│ │└────┴────────────────────────────────┘│ |
||
└──────┴───────────────────────────────────────┘</ |
└──────┴───────────────────────────────────────┘</syntaxhighlight> |
||
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: |
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' |
dow=: a:,~;:'monday tuesday wednesday thursday friday saturday sunday' |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="j"> dow |
||
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┬┐ |
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┬┐ |
||
│monday│tuesday│wednesday│thursday│friday│saturday│sunday││ |
│monday│tuesday│wednesday│thursday│friday│saturday│sunday││ |
||
└──────┴───────┴─────────┴────────┴──────┴────────┴──────┴┘</ |
└──────┴───────┴─────────┴────────┴──────┴────────┴──────┴┘</syntaxhighlight> |
||
Now everything is the same as before, except that we need to explicitly ignore the empty trailing element: |
Now everything is the same as before, except that we need to explicitly ignore the empty trailing element: |
||
< |
<syntaxhighlight lang="j"> echo ;:inv _2 _4 _5 {<S:0 dow |
||
sunday friday thursday |
sunday friday thursday |
||
echo ;:inv _2 _4 _5 {<S:0 col |
echo ;:inv _2 _4 _5 {<S:0 col |
||
red yellow green</ |
red yellow green</syntaxhighlight> |
||
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...). |
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 384: | Line 384: | ||
For example: |
For example: |
||
< |
<syntaxhighlight lang="j">nextItem=: {{ (x+1) -.#y }} |
||
nextLink=: {{ (1;x) #~ (L.y) > #x }} |
nextLink=: {{ (1;x) #~ (L.y) > #x }} |
||
Line 399: | Line 399: | ||
more=: {{'`next val more'=. ops['ops list position'=. y |
more=: {{'`next val more'=. ops['ops list position'=. y |
||
more position |
more position |
||
}}</ |
}}</syntaxhighlight> |
||
With this approach, one of the task examples could look like this: |
With this approach, one of the task examples could look like this: |
||
<syntaxhighlight lang="j"> |
|||
<lang J> |
|||
printAll=: {{ |
printAll=: {{ |
||
while. more y do. |
while. more y do. |
||
Line 431: | Line 431: | ||
monday |
monday |
||
value iterate^:3 DOW |
value iterate^:3 DOW |
||
thursday</ |
thursday</syntaxhighlight> 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.) |
(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.) |
||
Line 443: | Line 443: | ||
extensive set of functions which act on lists and vectors. Julia's Iterators can implement |
extensive set of functions which act on lists and vectors. Julia's Iterators can implement |
||
the C++ example: |
the C++ example: |
||
< |
<syntaxhighlight lang="julia">using DataStructures |
||
function PrintContainer(iterator) |
function PrintContainer(iterator) |
||
Line 473: | Line 473: | ||
FirstFourthFifth(reverse(days)) |
FirstFourthFifth(reverse(days)) |
||
FirstFourthFifth(reverse(colors)) |
FirstFourthFifth(reverse(colors)) |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
All elements: |
All elements: |
||
Line 492: | Line 492: | ||
five builtin data types it is not an issue for a routine to "know" what it is doing.<br> |
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. |
Something along the lines of [[Same_fringe#Phix]] could perhaps also be used to implement custom iterators. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<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 522: | Line 522: | ||
<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;">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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
Originally I used keys of 1..6 on the colours dictionary, but that looked suspicious. |
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". |
Note that the keys here are a mix of int/flt/string/seq, but still carefully "in order". |
||
Line 545: | Line 545: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="python">"""Iterables and iterators. Requires Python >= 3.6 for type hints.""" |
||
from collections import deque |
from collections import deque |
||
from typing import Iterable |
from typing import Iterable |
||
Line 666: | Line 666: | ||
if __name__ == "__main__": |
if __name__ == "__main__": |
||
main() |
main() |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 695: | Line 695: | ||
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. |
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. |
||
<lang |
<syntaxhighlight lang="raku" line>my %positional-iterable-types = |
||
array => [<Sunday Monday Tuesday Wednesday Thursday Friday Saturday>], |
array => [<Sunday Monday Tuesday Wednesday Thursday Friday Saturday>], |
||
list => <Red Orange Yellow Green Blue Purple>, |
list => <Red Orange Yellow Green Blue Purple>, |
||
Line 733: | Line 733: | ||
} |
} |
||
say @seq[^25];</ |
say @seq[^25];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Note: here we are iterating over the %positional-iterable-types hash, but |
<pre>Note: here we are iterating over the %positional-iterable-types hash, but |
||
Line 765: | Line 765: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
{{incorrect|Ring|The task is specifically about ''iterators'', not [[wp:Iterator#Contrasting_with_indexing|counting loops with indexing]].}} |
{{incorrect|Ring|The task is specifically about ''iterators'', not [[wp:Iterator#Contrasting_with_indexing|counting loops with indexing]].}} |
||
< |
<syntaxhighlight lang="ring"> |
||
list = [["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], |
list = [["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], |
||
["Red","Orange","Yellow","Green","Blue","Purple"]] |
["Red","Orange","Yellow","Green","Blue","Purple"]] |
||
Line 800: | Line 800: | ||
see "done..." +nl |
see "done..." +nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 826: | Line 826: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="ecmascript">import "./llist" for DLinkedList |
||
// Use iterators to print all elements of the sequence. |
// Use iterators to print all elements of the sequence. |
||
Line 862: | Line 862: | ||
System.print("\nReverse first, fourth, and fifth elements:") |
System.print("\nReverse first, fourth, and fifth elements:") |
||
printFirstFourthFifth.call(days[-1..0]) |
printFirstFourthFifth.call(days[-1..0]) |
||
printFirstFourthFifth.call(colors.reversed)</ |
printFirstFourthFifth.call(colors.reversed)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 885: | Line 885: | ||
as XPL0 can come to meeting the requirements of the task. |
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 |
\\ Use iterators to print all of the elements of any container that supports |
||
\\ iterators. It print elements starting at 'start' up to, but not |
\\ iterators. It print elements starting at 'start' up to, but not |
||
Line 928: | Line 928: | ||
FirstFourthFifth(@Days(7-1), -1); |
FirstFourthFifth(@Days(7-1), -1); |
||
FirstFourthFifth(@Colors(6-1), -1); |
FirstFourthFifth(@Colors(6-1), -1); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |