Skip to content

Commit 39e1473

Browse files
authored
make vector cmp match axes (#59500)
closes #48916 as suggested by @oscardssmith > I believe the more consistent behavior here would be for isless to error when comparing two Arrays a and b where eachindex(a,b)∉(eachindex(a), eachindex(b)) (similarly to how it works with Complex numbers or other collections like Dict that don't have an ordering.
1 parent d60a5f1 commit 39e1473

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

base/abstractarray.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3020,6 +3020,8 @@ function isequal(A::AbstractArray, B::AbstractArray)
30203020
end
30213021

30223022
function cmp(A::AbstractVector, B::AbstractVector)
3023+
ai1, bi1 = firstindex(A), firstindex(B)
3024+
isequal(ai1, bi1) || return cmp(ai1, bi1)
30233025
for (a, b) in zip(A, B)
30243026
if !isequal(a, b)
30253027
return isless(a, b) ? -1 : 1
@@ -3040,7 +3042,8 @@ end
30403042
"""
30413043
isless(A::AbstractVector, B::AbstractVector)
30423044
3043-
Return `true` when `A` is less than `B` in lexicographic order.
3045+
Return `true` when `A` is less than `B`. Vectors are first compared by
3046+
their starting indices, and then lexicographically by their elements.
30443047
"""
30453048
isless(A::AbstractVector, B::AbstractVector) = cmp(A, B) < 0
30463049

test/arrayops.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,6 +1465,18 @@ end
14651465
@test cmp([UInt8(1), UInt8(0)], [UInt8(0), UInt8(0)]) == 1
14661466
@test cmp([UInt8(1), UInt8(0)], [UInt8(1), UInt8(0)]) == 0
14671467
@test cmp([UInt8(0), UInt8(0)], [UInt8(1), UInt8(1)]) == -1
1468+
1469+
x = [1, 2, 3]
1470+
y = OffsetVector(x, -1)
1471+
@test cmp(x, y) == 1
1472+
@test cmp(y, x) == -1
1473+
@test !isless(x, y)
1474+
@test isless(y, x)
1475+
1476+
y2 = OffsetVector([1, 2, 3], 0)
1477+
@test cmp(x, y2) == 0
1478+
@test !isless(x, y2)
1479+
@test !isless(y2, x)
14681480
end
14691481

14701482
@testset "sort on arrays" begin

0 commit comments

Comments
 (0)