Iterators

You are viewing an old version of this entry, click here to see latest version.

An iterator is an object which follows the Iterator typedef (The type T is the iterated type) :

    typedef Iterator<T> = {
        function hasNext() : Bool;
        function next() : T;
    }

You can use the for syntax in order to execute iterators. The simplest iterator is the IntIter iterator which can easily be built using the operator ... (three dots). For example this will list all numbers from 0 to 9 :

    for( i in 0...10 ) {
    i = 0; // does not infinite loop
        // ...
    }

Or the usual for loop :

    for( i in 0...arr.length ) {
        foo(arr[i]);
    }

You don't need to declare the variable i before using a for, since it will be automatically declared. This variable will only be available inside the for loop.

Implementing Iterator

You can also define you own iterators. You can simply follow the Iterator typedef in your class by implementing the hasNext and next methods. Here is for example the IntIter class that is part of the standard library :

class IntIter {
    var min : Int;
    var max : Int;

    public function new( min : Int, max : Int ) {
        this.min = min;
        this.max = max;
    }

    public function hasNext() {
        return( min < max );
    }

    public function next() {
        return min++;
    }
}

Once your iterator is implemented, you can simply use it with the for...in syntax, this way :

    var iter = new IntIter(0,10);
    for( i in iter ) {
        // ...
    }

The variable name in the for is automatically declared and its type is bound to the iterator type. It is not accessible after the iteration is done.

Iterable Objects

If an object has a method iterator() taking no arguments and returning an iterator, it is said to be iterable. It doesn't have to implement any type. You can use a class directly in a for expression without the need to call the iterator() method:

    var a : Array<String> = ["hello","world","I","love","Haxe","!"];
    for( txt in a ) {
        tf.text += txt + " ";
    }

This sample will build the string by listing an array element using an iterator. It is the same as calling a.iterator() in the for expression.

= Important Notice


One important thing about Iterators the for loop variable is a copy of item from the iterable object and any assignments to it are lost.

«« Advanced Types | Properties »»

version #7980, modified 2010-02-04 11:33:30 by shelby