Iterators

From Rosetta Code
Iterators is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Iterators are a design pattern that can be used to access elements of a container without depending on the implementation or type of the container.

Task
  • Create an array like container to hold the days of the week and a linked-list like container to hold colors.
  • Print all of the elements of each container.
  • Print the first, fourth, and fifth elements of each container.
  • Print the last, fourth to last, and fifth to last of each container.


If you language supports iterators, use them. Otherwise show how access to elements can be separated from the containers that hold them.

C++

<lang cpp>#include <iostream>

  1. include <list>
  2. include <string>
  3. include <vector>

using namespace std;

// 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'. void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) {

 for(auto it = start; it != sentinel; ++it)
 {
   cout << *it << " "; 
 }
 cout << "\n";

}

// Use an iterator to print the first, fourth, and fifth elements void FirstFourthFifth(input_iterator auto it) {

 cout << *it;
 advance(it, 3);
 cout << ", " << *it;
 advance(it, 1);
 cout << ", " << *it;
 cout << "\n";

}

int main() {

 // Create two differnt kinds of containers of strings
 vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"};
 list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"};
 cout << "All elements:\n";
 PrintContainer(days.begin(), days.end());
 PrintContainer(colors.begin(), colors.end());
 
 cout << "\nFirst, fourth, and fifth elements:\n";
 FirstFourthFifth(days.begin());
 FirstFourthFifth(colors.begin());
 cout << "\nReverse first, fourth, and fifth elements:\n";
 FirstFourthFifth(days.rbegin());
 FirstFourthFifth(colors.rbegin());

} </lang>

Output:
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

Phix

Phix does not have iterators or for that matter design patterns. Since there are only five builtin data types it is not an issue for a routine to "know" what it is doing.

with javascript_semantics
procedure print_all(object s)
    if integer(s) then -- (a dictionary)
        s = apply(true,getd,{getd_all_keys(s),s})
    end if
    printf(1,"%s\n",join(s))
end procedure
 
procedure printFirstFourthFifth(object s, integer d=+1)
    if integer(s) then -- (a dictionary)
        s = apply(true,getd,{getd_all_keys(s),s})
    end if
    printf(1,"%s\n",join(extract(s,sq_mul({1,4,5},d))))
end procedure
 
sequence days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
integer colors = new_dict({{2,"Red"}, {2.5,"Orange"}, {3,"Yellow"}, {"a","Green"}, {"b","Blue"}, {{#CF},"Purple"}})
 
printf(1,"All elements:\n")
print_all(days)
print_all(colors)
 
printf(1,"\nFirst, fourth, and fifth elements:\n")
printFirstFourthFifth(days)
printFirstFourthFifth(colors)
 
printf(1,"\nReverse first, fourth, and fifth elements:\n")
printFirstFourthFifth(days,-1)
printFirstFourthFifth(colors,-1)

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".

Output:
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

Wren

Translation of: C++
Library: 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>

Output:
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