apple / swift-algorithms

Commonly used sequence and collection algorithms for Swift
Apache License 2.0
5.97k stars 443 forks source link

Chunked(by:) behavior seems incompatible with its documentation. #161

Closed tgrapperon closed 3 years ago

tgrapperon commented 3 years ago

The documentation of chunked(by:) states that the predicate is evaluated on consecutive elements. Experience and a naive look at the source are suggesting it is evaluated using the first element of the chunk instead of the previous one.

Steps to Reproduce

Let a: [Int] = [1,2,3,4,6,7,8,9] ("5" is missing). We want to chunk a such as two consecutive elements are consecutive numbers (their difference is exactly 1).

Expected behavior

[1,2,3,4,6,7,8,9].chunked(by: { $1 - $0 == 1 }) == [[1, 2, 3, 4], [6, 7, 8, 9]]

Actual behavior

[1,2,3,4,6,7,8,9].chunked(by: { $1 - $0 == 1 }) == [[1, 2], [3, 4], [6, 7], [8, 9]]

Am I understanding the documentation incorrectly, or is there an inconsistency between the documentation and the expected behavior?

timvermeulen commented 3 years ago

This looks like a bug to me, thanks for letting us know!