dfinity / motoko-base

The Motoko base library
Apache License 2.0
481 stars 100 forks source link

Why does Iter.fromArray not use xs.vals() #338

Open nomeata opened 2 years ago

nomeata commented 2 years ago

We currently have

  public func fromArray<A>(xs : [A]) : Iter<A> {
    var ix : Nat = 0;
    let size = xs.size();
    object {
      public func next() : ?A {
        if (ix >= size) {
          return null
        } else {
          let res = ?(xs[ix]);
          ix += 1;
          return res
        }
      }
    }
  };

but doesn’t that simply re-implement xs.vals()? Why not use that in this function?

ggreif commented 2 years ago

It is worse. We should make this public func fromArray<A>(xs : [A]) : Iter<A> = xs.vals(); and deprecate it. I suspect that the for loop optimisation I have implemented recently won't kick in for fromArray.

nomeata commented 2 years ago

Not sure we need to deprecate it; I think a nice, consistent and discoverable API is more important that an optimization – and we have plenty of optimization thwarted by unnecessary function indirections, just think of all the numeric operations. Maybe a simple inlining optimization for functions with very simple bodies would be useful.

I’d keep the function, adjust the implementation, and maybe mention in the docs that it is nothing else than the .vals() function.