haXe

Iterators

An iterator is an object which follow 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 most simple 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 ) {
        // ...
    }

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's 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 iterable. It doesn't have to implement any type. You can use such class directly into 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 elements using an iterator. It is same as calling a.iterator() in the for expression.

«« Advanced Types | Properties »»

version #1117, modified 2008-05-03 10:46:58 by ponticelli