motoko-base icon indicating copy to clipboard operation
motoko-base copied to clipboard

sequence-like collections should have a `group` operation that lumps together equal subsequences

Open ggreif opened this issue 1 year ago • 0 comments

Like Haskell's group.

Her is one implementation for arrays, that I came up with:

type Comp = { #less; #equal; #greater };
func group<A>(arr : [A], ca : (A, A) -> Comp) : [[A]] =
      switch (arr.size()) {
        case 0 [];
        case 1 [arr];
        case _ {
          let (outer, inner) = (Buffer.Buffer<[A]> 10, Buffer.Buffer<A> 5);
          let iter = arr.vals();
          let ?front = iter.next() else panic "BAD!";
          inner.add front;
          var cur = front;
          for (e in iter) {
            if (ca(cur, e) == #equal)
              inner.add e
            else {
              outer.add(inner.toArray());
              inner.clear();
              inner.add e;
              cur := e
            }
          };
          outer.add(inner.toArray());
          outer.toArray()
        }
    };

It should be easy to do the same for List.

This is also tracked as https://dfinity.atlassian.net/browse/LANG-331.

ggreif avatar Dec 03 '23 15:12 ggreif