dfinity / motoko-base

The Motoko base library
Apache License 2.0
480 stars 97 forks source link

Text slicing and iterators #56

Open rossberg opened 4 years ago

rossberg commented 4 years ago

Another observation from the hackathon is that folks need to split and slice strings, and we do not provide any way to do that other than converting to an array.

I propose:

Text.slice(begin : Iter, end : ?Iter) : Text

returns the text consisting of all characters between the begin iterator (inclusively) and the end iterator (exclusively). If end is null then the end of the text is used.

For this purpose, the character pointed to by an iterator is the one last returned by next. If that is null, it points to the end of the string.

Throws if begin or end are not text iterators, not iterators on equal text values, or iterators for which next has not yet been invoked.

The initial limbo state of an iterator is rather unfortunate in this context. Should we reconsider our iterator type?

nomeata commented 4 years ago

Right now, Iter is simply defined to be

public type Iter<T> = {next : () -> ?T};

do we want to change that, and make Iter an opaque subtype of {next : () -> ?T}? Or just do weird magic here?

rossberg commented 4 years ago

I was thinking weird magic, i.e., the function is a primitive that can look into the iter value somehow. I agree that's rather disgusting and cheating, though. Any better idea is highly welcome.