HaxeDoc2

(やまだぃちぅ) #1

Variablebis initialized to an array with the same values, but through a different comprehen-
sion style usingwhileinstead offor. Again, the following code would be equivalent:
1 var i = 0;
2 var a = [];
3 while(i < 10) a.push(i++);
The loop expression can be anything, including conditions and nested loops, so the following
works as expected:
1 class AdvArrayComprehension {
2 static public function main() {
3 var a =[
4 for (a in 1...11)
5 for(b in 2...4)
6 if (a % b == 0)
7 a+ "/" +b
8 ];
9 // [2/2,3/3,4/2,6/2,6/3,8/2,9/3,10/2]
10 trace(a);
11 }
12 }


6.7 Iterators


With Haxe it is very easy to define custom iterators and iterable data types. These concepts are
represented by the typesIteratorandIterablerespectively:
1 typedef Iterator={
2 function hasNext() : Bool;
3 function next() : T;
4 }
5
6 typedef Iterable={
7 function iterator() : Iterator;
8 }
Any class (2.3) which structurally unifies (3.5.2) with one of these types can be iterated over
using a for-loop (5.13). That is, if the class defines methodshasNextandnextwith matching re-
turn types it is considered an iterator, if it defines a methoditeratorreturning anIterator
it is considered an iterable type.
1 class MyStringIterator {
2 var s:String;
3 var i:Int;
4
5 public function new(s:String){
6 this.s = s;
7 i = 0;
8 }
9
10 public function hasNext() {
11 return i < s.length;

Free download pdf