I'm trying to understand why in Swift there are two different structures that are almost the same.
- Is SequenceOf not lazy?
- What are the intended uses for each?
Edit: I think I still don't understand what βlazyβ means in the sequence ... Fe take this code that uses SequenceOf, which is supposedly not lazy:
func myMap<S: SequenceType, V>(source: S, selector: S.Generator.Element -> V) -> SequenceOf<V> { let seq = SequenceOf { _ -> GeneratorOf<V> in var gen = source.generate() return GeneratorOf { let v = gen.next() println(v) return v == nil ? nil : selector(v!) } } return seq }
Let me call him
let a = myMap([1, 2, 3], { $0 * 2 }) var gen = a.generate() let v1 = gen.next() let v2 = gen.next()
He is typing
Optional (1)
Optional (2)
It seems lazy to me ...
Edit # 2:
When using the card in a lazy sequence, it seems to be eagerly evaluating the elements:
struct TransientView<S: SequenceType> : SequenceType { private let seq: S init(_ seq: S) { self.seq = seq } func generate() -> GeneratorOf<S.Generator.Element> { var g = seq.generate() return GeneratorOf { println("next") return g.next() } } } let seq = lazy(map(TransientView([1, 2, 3]), { $0 * 2 }))
prints "next" 4 times ...
Change No. 3. Here is my current example: it would be wrong to say that "SequenceOf is not lazy." Most likely, "SequenceOf is expanded with lazy .map, .filter, etc.". It is possible to write lazy versions of maps, files, etc., which will apply to any sequence, including SequenceOf. But Apple decided to apply the βlazyβ paradigm not only to sequence instances, but also to sequence elements, so if you specify a sequence variable as lazy, LazySequence is used and, since such extensions are lazy. I think this is the wrong approach, and a lazy declaration should not be passed on to elements - instead, elements should be kept lazy as long as possible. It is easy to turn lazy into impatient, but impossible.
swift
Sergey Aldoukhov
source share