On Thu, Dec 31, 2015, at 12:36 AM, Dave Abrahams wrote: >> On Dec 30, 2015, at 3:57 PM, Kevin Ballard via swift-evolution >> <[email protected]> wrote: >> >> It's sometimes useful to get the first element of a sequence. To that >> end I'd like to propose >> >> extensionSequenceType { /// Returns the first element of >> `self`, or `nil` if `self` is empty. /// - Complexity: O(1) var >> first: Self.Generator.Element? { var gen = generate() return >> gen.next() } } >> >> I think it makes sense to add this property to the definition of >> SequenceType as well, so various sequences can override it to avoid >> constructing a generator. >> >> With this added to SequenceType, we can remove it from >> CollectionType, as the behavior will be the same. > > Property accesses should not mutate the receiver, and because of how > Sequences work, inspecting first may consume the first element.
Fair enough. Swift does support `mutating get`, but it looks like the stdlib doesn't actually use this anywhere (at least, in the public API). Still, it's a shame that there's no way to do this generically for sequences. It's something I need upon occasion. I wish I could actually say something like `seq.generate().next()`, but you can't call mutating functions on temporaries. I'd be tempted to say we should have a `func first()` method, except then CollectionTypes would have both a property and a method named `first` and that would just be confusing. > I suggest you consider adding a BufferedSequence<Base: SequenceType> > that has a stable first property (at least until it is iterated) 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. 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. -Kevin Ballard
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
