Why are empty ranges normalized?

What the motivation for this normalization?

julia> 5:1
1 Like

There is a comment in the source code that this “simplifies arithmetic for Signed numbers”. This dates back to Make StepRange safe for more number types by timholy · Pull Request #17611 · JuliaLang/julia · GitHub

For example, length(r) can be computed by last(r) - first(r) + 1 for unit-step ranges.


Oh, I have stepped in this landmine before. I had some code that passed two numbers around that were often used to define a range, so I started passing them around as a range. When the range was empty I still needed/wanted to know which were the values for other computations. Almost got crazy debugging not understanding where my data was getting corrupted.

1 Like

Since we only normalize in certain cases, and thus cannot rely on it generally, we could consider removing the normalization, if you want to make a PR to try

1 Like

This is not quite true - e.g. typemin(Int):typemax(Int) will return the wrong result.

1 Like

This doesn’t look good:

julia> length(typemin(Int)+1:0)

julia> length(0:typemax(Int))

but then what can we do while staying type stable… I guess throwing an error would be better.