on Mon Aug 29 2016, Tim Vermeulen <swift-evolution@swift.org> wrote:

> The intent of my function wasn’t very clear, but it was supposed to
> return a sequence that contains *all* consecutive pairs, i.e. (0 ..<
> 4).pairs would result in [(0, 1), (1, 2), (2, 3)].

extension Sequence {
  typealias Element = Iterator.Element
  
  /// All adjacent pairs of elements, in order.
  var allAdjacentPairs: UnfoldSequence<(Element, Element), (i: Iterator, e: 
Element?)> {
    var i = makeIterator()
    let e = i.next()
    
    return sequence(state: (i, e)) {
      (s: inout (i: Iterator, e: Element?))->(Element, Element)? in
      let e = s.i.next()
      defer { s.e = e }
      return e.map { (s.e!, $0) }
    }
  }
}

for j in 0..<10 {
  print(Array((0..<j).allAdjacentPairs))
}

HTH,

-- 
-Dave

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to