[swift-evolution] Passing an optional first argument to sequence(first:next:)

Dave Abrahams dabrahams at apple.com
Thu Sep 1 17:47:58 CDT 2016


on Mon Aug 29 2016, Tim Vermeulen <swift-evolution at 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))
}


-- 
-Dave



More information about the swift-evolution mailing list