# Should there be BidirectionalCollection.dropLast(while:)?

**URL:** <https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059>\
**Category:** Using Swift\
**Created:** [May 10, 2021, 8:41pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059 "2021-05-10T20:41:13Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [May 10, 2021, 8:41pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/1 "2021-05-10T20:41:13Z")

</div>

There is `Collection.drop(while:)` which drops elemenst from the beginning.

Look like [Swift Algorithms](https://forums.swift.org/c/related-projects/algorithms/70) added `BidirectionalCollection.suffix(while:)`

I think for symmetry and completeness, there should be `BidirectionalCollection.dropLast(while:)`

I needed this so I made one like this:

```swift
extension BidirectionalCollection {
    func dropLast(while predicate: (Element) throws -> Bool) rethrows -> Self.SubSequence {
        let suffix = try suffix(while: predicate)
        return dropLast(suffix.count)
    }
}

```

is there correct? is there better way?

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [May 10, 2021, 9:01pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/2 "2021-05-10T21:01:35Z")

</div>

> [@young](#):
>
> is there better way?

Avoid calling `count` on a non-`RandomAccess` collection, by leveraging the fact that a slice shares indices with its base collection:

```swift
return self[..<suffix.startIndex]

```

Or, using only standard library methods:

```swift
let i = try lastIndex{ try !predicate($0) }

guard let j = i else {
  return self[..<startIndex]
}

return self[...j]

```

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [May 10, 2021, 9:34pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/3 "2021-05-10T21:34:46Z")

</div>

I don't understand why this works to return the whole thing as `Subsequence`:

```swift
return self[..<startIndex] // why is the range result in the entire thing as Subsequence?

```

is it because `..<startIndex` is an empty range? Then shouldn't it be an empty `Subsequence`?

these two I can understand:

```swift
return self[..<endIndex]
return self[...] // I prefer this form

```

Thanks for the answer, I learned something new about when not to use `count`

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [May 10, 2021, 9:58pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/4 "2021-05-10T21:58:28Z")

</div>

> [@young](#):
>
> I don't understand why this works to return the whole thing as `Subsequence` :
> 
> ```swift
> return self[..<startIndex] // why is the range result in the entire thing as Subsequence?
> 
> ```
> 
> is it because `..<startIndex` is an empty range? Then shouldn't it be an empty `Subsequence` ?

It returns an empty subsequence.

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [May 10, 2021, 11:36pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/5 "2021-05-10T23:36:40Z")

</div>

okay, I understand now. The `guard ... else { }` is executed when every element in the collection match the predicate, so an empty `Subsequence` is returned.

🙏

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [April 19, 2022, 7:50pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/6 "2022-04-19T19:50:12Z")

</div>

> [@young](#):
>
> I think for symmetry and completeness, there should be `BidirectionalCollection.dropLast(while:)`

Agreed!

> is there a better way?

Your original is nearly perfect:

```swift
extension BidirectionalCollection {
    func dropLast(while predicate: (Element) throws -> Bool) rethrows -> Self.SubSequence {
        let suffix = try suffix(while: predicate)
        return self[..<suffix.startIndex]
    }
}

```

I might write @Nevin's suggestion this way:

```swift
extension BidirectionalCollection {
    func dropLast(while predicate: (Element) throws -> Bool) rethrows -> Self.SubSequence {
        let end = try lastIndex{ try !predicate($0) }.map(index(after:)) ?? startIndex
        return self[..<end]
    }
}

```

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [April 19, 2022, 9:59pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/7 "2022-04-19T21:59:18Z")

</div>

> [@dabrahams](#):
>
> `let end = try lastIndex{ try !predicate($0) } ?? endIndex`

should `endIndex` be `startIndex` to return an empty collection? I think when `lastIndex(where:)` is nil, you are returning the whole collection. It should be empty.

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [April 19, 2022, 11:03pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/8 "2022-04-19T23:03:58Z")

</div>

You're quite right, thanks

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [April 19, 2022, 11:28pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/9 "2022-04-19T23:28:53Z")

</div>

> [@dabrahams](#):
>
> `return self[..<end]`

I think there is an off-by-one error: when `lastIndex(where:)` found an index, that index position need to be included in the `SubSequence`. This is what I did:

```swift
extension BidirectionalCollection {
    func droppedLast(while predicate: (Element) throws -> Bool) rethrows -> SubSequence {
        try lastIndex(where: { try !predicate($0) }).map { self[...$0] } ?? self[..<startIndex]
    }
}

```

---

<div class="post-metadata">

**Author:** ![nnnnnnnn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nnnnnnnn/32/264_2.png) [@nnnnnnnn](https://forums.swift.org/u/nnnnnnnn)\
**Post date:** [April 20, 2022, 1:26am UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/10 "2022-04-20T01:26:16Z")

</div>

The Algorithms package does include this method, with the name `trimmingSuffix(while:)` ([implemented here](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Trim.swift#L119-L140)). The package includes a variety of trimming methods, including `trimmingPrefix(while:)` — a method that shares the functionality of `drop(while:)` but is more predictably readable at the call site when written with a trailing closure.

Related to the implementation conversation in this thread, we discovered that there are a couple common operations that are used in implementing this kind of functionality: `endOfPrefix(while:)` and `startOfSuffix(while:)` ([implemented here](https://github.com/apple/swift-algorithms/blob/c5ea9e3e36b5333073ecc2f551a2b93e8d88a021/Sources/Algorithms/Suffix.swift#L34-L88)). `startOfSuffix(while:)` handles that off-by-one case without recalculating the trailing index.

---

<div class="post-metadata">

**Author:** ![young](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/young/32/7878_2.png) [@young](https://forums.swift.org/u/young)\
**Post date:** [April 20, 2022, 3:49pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/11 "2022-04-20T15:49:10Z")

</div>

Why are `endOfPrefix(while:)` and `startOfSuffix(while:)` `internal`? They seem to be generally useful.

---

<div class="post-metadata">

**Author:** ![nnnnnnnn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nnnnnnnn/32/264_2.png) [@nnnnnnnn](https://forums.swift.org/u/nnnnnnnn)\
**Post date:** [April 20, 2022, 4:14pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/12 "2022-04-20T16:14:53Z")

</div>

Honestly, we just weren't sure if we had the names right or not. They should probably be public!

---

<div class="post-metadata">

**Author:** ![scanon](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/scanon/32/2445_2.png) [@scanon](https://forums.swift.org/u/scanon)\
**Post date:** [April 20, 2022, 4:27pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/13 "2022-04-20T16:27:07Z")

</div>

Should @young file an issue to request they be made public?

---

<div class="post-metadata">

**Author:** ![nnnnnnnn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nnnnnnnn/32/264_2.png) [@nnnnnnnn](https://forums.swift.org/u/nnnnnnnn)\
**Post date:** [April 20, 2022, 7:34pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/14 "2022-04-20T19:34:57Z")

</div>

That would be great! @young, feel free to start a thread in the Swift Algorithms discussion, file an issue, or open a PR to make the change. Happy to discuss in any of those places.

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [April 21, 2022, 7:25pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/15 "2022-04-21T19:25:03Z")

</div>

> [@young](#):
>
> I think there is an off-by-one error: when `lastIndex(where:)` found an index, that index position need to be included in the `SubSequence` .

Bah, that's what I get for hastyposting. Thanks for fixing my errors!

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [April 21, 2022, 7:40pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/16 "2022-04-21T19:40:08Z")

</div>

Here's a more elegant one that additionally shows why it's [important to expose the `base`s](https://forums.swift.org/t/pitch-have-all-adapters-in-the-standard-library-uniformly-expose-their-base/56830) of the standard library's adapter types:

```swift
extension BidirectionalCollection {
    func dropLast(while predicate: (Element) throws -> Bool) rethrows -> Self.SubSequence {
      let head = try self.reversed().drop(while: predicate)
      return self[head.endIndex.base..<head.startIndex.base]
    }
}

```

---

<div class="post-metadata">

**Author:** ![dabrahams](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dabrahams/32/9815_2.png) [@dabrahams](https://forums.swift.org/u/dabrahams)\
**Post date:** [May 15, 2022, 6:44pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/17 "2022-05-15T18:44:00Z")

</div>

At the C++Now conference 2 weeks ago, I attended a talk I thought I was going to hate: “[Why iterators got it all wrong and what we should use instead](https://cppnow.digital-medium.co.uk/session/why-iterators-got-it-all-wrong-and-what-we-should-use-instead/)” by Arno Schoedl. Turns out it was pretty brilliant in fact, and I think it helps explain how I posted several wrong answers in this thread: a fuzziness in the role of indices makes them error-prone. I don't love some details of the library design he proposes (and I think he's gone on to revise those details out since the conference), but his fundamental insight, that sometimes an index represents the position of an element and other times it represents the boundary between elements, is extremely powerful. If Swift ever gets around to revising its collection model, these insights should be taken into consideration.

/cc @lorentey @scanon

---

<div class="post-metadata">

**Author:** ![ole](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ole/32/18720_2.png) [@ole](https://forums.swift.org/u/ole)\
**Post date:** [June 20, 2022, 9:03pm UTC](https://forums.swift.org/t/should-there-be-bidirectionalcollection-droplast-while/48059/18 "2022-06-20T21:03:22Z")

</div>

> [@dabrahams](#):
>
> At the C++Now conference 2 weeks ago, I attended a talk I thought I was going to hate: “[Why iterators got it all wrong and what we should use instead](https://cppnow.digital-medium.co.uk/session/why-iterators-got-it-all-wrong-and-what-we-should-use-instead/)” by Arno Schoedl.

The recording of this talk is now available: [https://www.youtube.com/watch?v=TZ\_m6\_IGwX0](https://www.youtube.com/watch?v=TZ_m6_IGwX0)

(YouTube currently shows it as "unlisted"; I got the link from [JetBrains's conference page](https://pages.jetbrains.com/cppnow2022), where some videos have been pre-published. I believe the YouTube link won't change once it goes fully public.)
