【问题标题】:Concatenating lazy sequences in swift?快速连接惰性序列?
【发布时间】:2019-06-12 13:04:05
【问题描述】:

我希望能够执行[1, 2, 3].lazy + [4, 5, 6].lazy 而不是([1, 2, 3] + [4, 5, 6]).lazy 之类的操作,因为假设的前者操作是恒定的,而后者是线性的。

【问题讨论】:

  • [seq1, seq2].joined() 可能是您要查找的内容,但假设性较小的示例会有所帮助。

标签: swift sequence


【解决方案1】:

正如 Martin 指出的那样,使用 Sequence.joined() 是正确的选择。您可以使用我制作的这些垫片来确认它确实是惰性的:

struct PrintingSequence<S: Sequence>: Sequence {
    let wrapped: S

    init(_ wrapped: S) {
        print("Making a sequence wrapping \(wrapped) of type \(S.self)")
        self.wrapped = wrapped
    }

    func makeIterator() -> PrintingIterator<S.Iterator> {
        return PrintingIterator(wrapped.makeIterator())
    }
}

struct PrintingIterator<I: IteratorProtocol>: IteratorProtocol {
    var wrapped: I


    init(_ wrapped: I) {
        print("\nMaking an iterator wrapping \(wrapped) of type \(I.self)")
        self.wrapped = wrapped
    }

    mutating func next() -> I.Element? {
        let result = self.wrapped.next()
        print("Yielding \(result as Any)")
        return result
    }
}

let joinedSequence = [
    PrintingSequence([1, 2, 3].lazy),
    PrintingSequence([4, 5, 6].lazy)
].joined()

var joinedIterator = joinedSequence.makeIterator()

print("\nAbout to start the loop")
while let i = joinedIterator.next() {
    print("\tloop \(i)")
}

哪些打印:

Making a sequence wrapping LazySequence<Array<Int>>(_base: [1, 2, 3]) of type LazySequence<Array<Int>>
Making a sequence wrapping LazySequence<Array<Int>>(_base: [4, 5, 6]) of type LazySequence<Array<Int>>

About to start the loop

Making an iterator wrapping IndexingIterator<Array<Int>>(_elements: [1, 2, 3], _position: 0) of type IndexingIterator<Array<Int>>
Yielding Optional(1)
    loop 1
Yielding Optional(2)
    loop 2
Yielding Optional(3)
    loop 3
Yielding nil

Making an iterator wrapping IndexingIterator<Array<Int>>(_elements: [4, 5, 6], _position: 0) of type IndexingIterator<Array<Int>>
Yielding Optional(4)
    loop 4
Yielding Optional(5)
    loop 5
Yielding Optional(6)
    loop 6
Yielding nil

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 2014-11-10
    • 2016-09-19
    • 2018-11-13
    • 2012-05-20
    相关资源
    最近更新 更多