Iterators: Difference between revisions

Added Wren
(Create Iterators task)
 
(Added Wren)
Line 80:
Saturday, Wednesday, Tuesday
Purple, Yellow, Orange
</pre>
 
=={{header|Wren}}==
{{trans|C++}}
{{libheader|Wren-llist}}
In Wren an ''iterable object'' is a sequence whose class implements the ''iterate'' and ''iteratorValue'' methods. These methods enable one to walk through the sequence and look up the value of the each element.
 
Iterable objects, which include the built-in classes: List, Range and String, generally inherit from the Sequence class which provides a number of useful methods including: map, where and reduce.
 
Wren has no built-in linked list class but the Wren-llist module provides singly and doubly-linked implementations of them. Nor does it have a built-in way to iterate through a sequence in reverse though it is possible to write one. Here, we simply reverse the sequence first to do this.
 
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.
<lang ecmascript>import "./llist" for DLinkedList
 
// Use iterators to print all elements of the sequence.
var printAll = Fn.new { |seq|
var iter = null
while (iter = seq.iterate(iter)) System.write("%(seq.iteratorValue(iter)) ")
System.print()
}
 
// Use iterators to print just the first, fourth and fifth elements of the sequence.
var printFirstFourthFifth = Fn.new { |seq|
var iter = null
iter = seq.iterate(iter)
System.write("%(seq.iteratorValue(iter)) ") // first
for (i in 1..3) iter = seq.iterate(iter)
System.write("%(seq.iteratorValue(iter)) ") // fourth
iter = seq.iterate(iter)
System.print(seq.iteratorValue(iter)) // fifth
}
 
// built in list (elements stored contiguously)
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
 
// custom doubly linked list
var colors = DLinkedList.new(["Red", "Orange", "Yellow", "Green", "Blue", "Purple"])
 
System.print("All elements:")
printAll.call(days)
printAll.call(colors)
 
System.print("\nFirst, fourth, and fifth elements:")
printFirstFourthFifth.call(days)
printFirstFourthFifth.call(colors)
 
System.print("\nReverse first, fourth, and fifth elements:")
printFirstFourthFifth.call(days[-1..0])
printFirstFourthFifth.call(colors.reversed)</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>
9,476

edits