UnitRange behavior

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

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

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

2 Likes

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

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

1 Like

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.

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.

3 Likes

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

1 Like

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 Non-transitive operator precedence · Issue #18714 · JuliaLang/julia · GitHub

10 Likes

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

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.