Addition and UnitRange

Is there a reason, why (1:23) * 2 works, but not (1:23) + 2?

Do you mean something like:

import base.+
+(r::UnitRange{Int64}, i::Int64)= (first(r)+i):(last(r)+i)

I don’t know if there is a reason :wink:

This is the same as

julia> [1,2] + 2
ERROR: MethodError: no method matching +(::Array{Int64,1}, ::Int64)

Just use broadcasting.

The reason is the general one behind not defining “vectorized” versions of functions, which led to the introduction of broadcasting as the idiomatic solution.

This is better handled by broadcasting which has been customized to be efficient in this case (note the type of the result):

julia> (1:23) .+ 2

Also, what you are suggesting is technically type piracy.


I see, makes sense, thanks :-).

The reason why the multiplication is implemented is probably due to the following:

julia> (1:4) * 2

julia> (1:4) .* 2

julia> (1:4) .+ 2

EDIT: No, it doesn’t make sense that there is an extra multiplication implemented…

Multiplying a vector by a scalar is considered a meaningful operation on its own (eg in a vector space) so it has a method.