UnitRange behavior


#1

Can’t be right, right?

julia> 1.0:5 .- 0.5
1.0:1.0:4.0

julia> collect(1.0:5) .- 0.5
5-element Array{Float64,1}:
 0.5
 1.5
 2.5
 3.5
 4.5

#2

Try adding parentheses around the range in the first example — it’s a precedence thing.


#3

Yes, that’s it but quite unexpected, at least to me.


#4

If you’re coming from MATLAB, e.g., this is the very expected thing!


#5

Agreed. I’ve been caught on it too. That’s how I knew :slight_smile:


#6

I must confess. I have many years of Matlab and, damn it, I had never noticed that. Who knows why, probably there I never missed the parentheses but here in Julia I was expecting a different thing.


#7

Yeah, I generally end up adding parentheses for complicated ranges because the precedence isn’t always obvious.

On the other hand, the current behavior allows you to do:

for i in 1:N-1
  ...
end

which feels pretty natural.


#8

Presumably you’ve written 1:n-1 or a+1:n?


#9

I like the Fortress idea where whitespace which is inconsistent with precedence is a syntax error: this would have caught the original example here.

See also https://github.com/JuliaLang/julia/issues/18714


#10

Yes, I really like that too. It would be breaking though so it would have to be opt-in or wait until 2.0.


#11

No. I can’t reconstruct it anymore but it involved something like this

julia> x=1:5;

julia> x - 0.5
┌ Warning: `a::AbstractArray - b::Number` is deprecated, use `a .- b` instead.
│   caller = top-level scope at none:0
└ @ Core none:0
0.5:1.0:4.5

which fixed in my head the array array side of this and then later using 1:5 .- 0.5 and being surprised that the results were different. Being late at night might had influenced too.