[swift-evolution] Proposal: Add SequenceType.first

Kevin Ballard kevin at sb.org
Thu Dec 31 17:20:13 CST 2015

On Thu, Dec 31, 2015, at 02:03 PM, Dave Abrahams wrote:
>> On Dec 31, 2015, at 1:58 PM, Kevin Ballard <kevin at sb.org> wrote:
>> Good idea, though I'd probably call it PeekSequence because it would
>> only buffer a single element (and BufferedSequence sounds like it's
>> got an arbitrary-sized buffer). Perhaps more useful would be the
>> associated PeekGenerator, because peek() is a useful thing to have
>> when writing custom generator-using code.
> The size of the buffer is an implementation detail, and I don’t find
> “peek” descriptive.

There's precedent for the name "peek". More importantly, that's the name
you'd use for the generator method; the sequence would still have the
"first" property.

My concern with making the size of the buffer be an implementation
detail is I'd rather not add array allocation if I only need a single
element of lookahead. I suppose it could have an `enum {
OneElement(Element), Buffer([Element]) }` as the storage, but that still
does end up being a little bit of extra work on every call to next().

>> I'll write up a more detailed email with a proposed design in a
>> minute.
>>> Another related adapter I’d like to add is a model of CollectionType
>>> that is backed by a sequence and lazily populated in fixed-sized
>>> chunks.
>> Also a good idea. Although really it could just be backed by a
>> ContiguousArray, those things already grow in chunks. I'll write up a
>> design for that too.
> Not unless you want to keep the buffers alive longer than necessary.
> Imagine you’re parsing a long stream with some amount of lookahead.
> You can scan this collection by slicing it and the buffer segments
> that are no longer in use will be automatically collected.

Ah, I didn't realize you wanted to collect chunks that haven't been used
lately. But I don't think that's possible; since it's backed by a
sequence, the chunks MUST be generated in order; there's no way to skip
ahead, and no way to generate an older chunk that you've thrown away.
But since it's a CollectionType, you need to preserve the ability to
access older values. So the only way to actually have this be a
CollectionType is to buffer the entire sequence up to the highest-
accessed index.

Of course, your use-case of processing a stream with some amount of
lookahead and throwing away the old data actually sounds like something
a "BufferedSequence" might provide. Or actually, a "BufferedGenerator",
because the only way to process a sequence is with a generator and so
all a "BufferedSequence" would really do is just give you a
"BufferedGenerator" from its generate() method.

-Kevin Ballard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151231/84b59e44/attachment.html>

More information about the swift-evolution mailing list