 extension LazyChunked: BidirectionalCollection
   where Base: BidirectionalCollection
 {
-  /// Returns the index in the base collection for the element that starts
-  /// the chunk ending at the given index.
+  /// Returns the index in the base collection of the start of the chunk ending
+  /// at the given index.
   @usableFromInline
   internal func startOfChunk(endingAt end: Base.Index) -> Base.Index {
+    let indexBeforeEnd = base.index(before: end)
+    
     // Get the projected value of the last element in the range ending at `end`.
-    let lastOfPreviousChunk = base[base.index(before: end)]
+    let subject = projection(base[indexBeforeEnd])
     
     // Search backward from `end` for the first element whose projection isn't
-    // equal to `lastOfPreviousChunk`.
-    if let firstMismatch = base[..<end]
-      .lastIndex(where: { !belongInSameGroup($0, lastOfPreviousChunk) })
+    // equal to `subject`.
+    if let firstMismatch = base[..<indexBeforeEnd]
+      .lastIndex(where: { !belongInSameGroup(projection($0), subject) })
     {
       // If we found one, that's the last element of the _next_ previous chunk,
       // and therefore one position _before_ the start of this chunk.

  @inlinable
  public func chunked<Subject: Equatable>(
    on projection: @escaping (Element) -> Subject
  ) -> LazyChunked<Elements> {
    LazyChunked(
      base: elements,
      belongInSameGroup: { projection($0) == projection($1) })
  }
}


//
//===----------------------------------------------------------------------===//

public struct LazyChunked<Base: Collection, Subject> {
  /// The collection that this instance provides a view onto.
  public let base: Base
  
  /// The projection function.
  @usableFromInline
  internal let projection: (Base.Element) -> Subject
  
  /// The predicate.
  @usableFromInline
  internal let belongInSameGroup: (Subject, Subject) -> Bool
  
  @usableFromInline
  internal init(
    base: Base,
    projection: @escaping (Base.Element) -> Subject,
    belongInSameGroup: @escaping (Subject, Subject) -> Bool
  ) {
    self.base = base
    self.projection = projection
    self.belongInSameGroup = belongInSameGroup
  }
}
