[swift-evolution] Lazy flatMap for Optionals
Donnacha Oisín Kidney
oisin.kidney at gmail.com
Fri Dec 4 16:38:44 CST 2015
Currently, several of the methods on SequenceType in the standard library have lazy variants. flatMap, though, (seems) to have a version missing: while there’s a lazy version for nested sequences, there’s no lazy version for sequences of Optionals. Is there maybe a reason for this that I haven’t thought of? At any rate, here’s what I had in mind:
public struct FlatMapOptionalGenerator<G: GeneratorType, Element>: GeneratorType {
private let f: G.Element -> Element?
private var g: G
public mutating func next() -> Element? {
while let x = g.next() {
if let y = f(x) {
return y
}
}
return nil
}
}
public struct FlatMapOptionalSequence<S: LazySequenceType, Element>: LazySequenceType {
private let f: S.Generator.Element -> Element?
private let s: S
public func generate() -> FlatMapOptionalGenerator<S.Generator, Element> {
return FlatMapOptionalGenerator(f: f, g: s.generate())
}
}
extension LazySequenceType {
public func flatMap<T>(transform: Generator.Element -> T?) -> FlatMapOptionalSequence<Self, T> {
return FlatMapOptionalSequence(f: transform, s: self)
}
}
Does this seem like a good idea?
Oisin.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151204/80612439/attachment.html>
More information about the swift-evolution
mailing list