Swift 2b2: Conforming LazySequence and Lazy*Collection to a LazySequenceType protocol enables better extensions

Originator:rix.rob
Number:rdar://21671072 Date Originated:03-Jul-2015 02:04 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode-beta (7A121l)
Classification:Enhancement Reproducible:Always
 
Summary:
I wanted a scan method, so I wrote myself a ScanSequenceView and added my scan method to an extension of SequenceType:

extension SequenceType {
	func scan<T>(initial: T, combine: (T, Generator.Element) -> T) -> ScanSequenceView<Self, T>
}

Then I wanted it to be lazy, so I wrote a LazySequence extension with a scan method:

extension LazySequence {
	func scan<T>(initial: T, combine: (T, Generator.Element) -> T) -> LazySequence<ScanSequenceView<LazySequence<S>, T>> { … }
}

But my tests of its laziness failed, because lazy([ 0, 1, 2 ]).scan(…) isn’t calling the LazySequence implementation, it’s calling the SequenceType implementation, because [Int] is a RandomAccessCollection and thus lazy([ 0, 1, 2 ]) returns a LazyRandomAccessCollection. There is no relationship between LazyRandomAccessCollection and LazySequence; they are entirely disjoint.

A LazySequenceType protocol joins them back up:

public protocol LazySequenceType: SequenceType {
	typealias Sequence: SequenceType
}

extension LazySequenceType {
	public func scan<T>(initial: T, combine: (T, Generator.Element) -> T) -> LazySequence<ScanSequenceView<Self, T>> {
		return lazy(ScanSequenceView(sequence: self, initial: initial, combine: combine))
	}
}

extension LazySequence: LazySequenceType {
	public typealias Sequence = S
}

extension LazyForwardCollection: LazySequenceType {
	public typealias Sequence = S
}

extension LazyBidirectionalCollection: LazySequenceType {
	public typealias Sequence = S
}

extension LazyRandomAccessCollection: LazySequenceType {
	public typealias Sequence = S
}


Please relate LazySequence and the various Lazy*Collections such that we can extend them once, like how extending SequenceType with scan() extended CollectionType instances too.


Steps to Reproduce:
N/A

Expected Results:
N/A

Actual Results:
N/A

Regression:
N/A

Notes:
Fortunately this is something that app & library authors can undertake for themselves, as witnessed by the code I wrote above actually functioning. I think it should be in the standard library regardless, however.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!