HaxeFoundation / haxe.org-comments

Repository to collect comments of our haxe.org websites
2 stars 2 forks source link

[haxe.org/manual] Iterators #77

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Iterators - Haxe - The Cross-platform Toolkit

Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.

https://haxe.org/manual/lf-iterators.html

daverave1212 commented 3 years ago

So is there a way to use an iterator twice without manually resetting it?

markknol commented 3 years ago

Normally you use an iterator per loop, and if you mark its functions as inline there is no instance at runtime. If there is no instance, there is also no need to recycle it.

If you take the example and add inline to it, it will look like this:

class MyStringIterator {
  var s:String;
  var i:Int;

  public inline function new(s:String) {
    this.s = s;
    i = 0;
  }
  public inline function hasNext() return i < s.length;
  public inline function next() return s.charAt(i++);
}

class Test {
  static public function main() {
    var label = Math.random() > 0.5 ? "apple" : "pear";
    for (chr in new MyStringIterator(label)) {
      trace(chr);
    }
  }
}

It will be compiled like this:

// Generated by Haxe 4.1.4
(function ($global) { "use strict";
class Main {
    static main() {
        let _g_s = Math.random() > 0.5 ? "apple" : "pear";
        let _g_i = 0;
        while(_g_i < _g_s.length) console.log(_g_s.charAt(_g_i++));
    }
}
Main.main();
})({});
c-g-dev commented 6 months ago

For most purposes you can probably get away with resetting in hasNext() itself.

public function hasNext():Bool {
        if(this.data.length <= this.currentIdx){
            this.currentIdx = 0;
            return false;
        }
        return true;
}

I haven't been able to find a case where that doesn't work.