Stop of a range with length 0

Just curious:

For the following kind of ranges of length 0, please note the submitted stop and returned

julia> 12:1:**3**
12:1:**11**

julia> range(12,**stop=3**;step = 1)
12:1:**11**

Is this by design?

_range(start::Any , step::Any , stop::Any , len::Nothing) = range_start_step_stop(start, step, stop)

range_start_step_stop(start, step, stop) = start:step:stop

Thanks.

Yes, the StepRange constructor calls steprange_last(start, step, stop) to recompute the stop value. The purpose is to have 1 unique instance represent each non-empty sequence; this makes comparisons 1:2:4 === 1:2:3 easier, which helps things like hashing. An empty sequence does not have 1 unique instance, but that call does limit the variability of stop relative to start.

1 Like

So all ranges of length zero, regardless of their start, stop and step values, are considered equal - the reasons make sense, thanks.

Good to be aware not to expect range stop getting round-tripped under all conditions.

Thanks!

You get equal for all zero length ranges since they represent the same value (a range with no items).
You get identical only for zero length ranges with the same start and step, since they are stored exactly the same.

julia> 5:2:4 == 5:2:3
true

julia> 4:2:3 == 5:2:3
true

julia> 5:1:4 == 5:2:4
true

julia> 5:2:4 === 5:2:3
true

julia> 4:2:3 === 5:2:3
false

julia> 5:1:4 === 5:2:4
false
2 Likes