Iterators: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(3 intermediate revisions by 3 users not shown)
Line 118:
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}}==
Line 645 ⟶ 672:
 
(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 697 ⟶ 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 1,037 ⟶ 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.
<syntaxhighlight lang="ecmascriptwren">import "./llist" for DLinkedList
 
// Use iterators to print all elements of the sequence.
9,479

edits