Skip to content

Incorrect broadcasted Period subtraction behaviour? #12094

@GordStephen

Description

@GordStephen

The behaviour for broadcasted Period subtraction is currently

julia> Day(1) - [Day(2), Day(3)]
2-element Array{Base.Dates.Day,1}:
 1 day 
 2 days

and

julia> Day(1) .- [Day(2), Day(3)]
2-element Array{Base.Dates.Day,1}:
 1 day 
 2 days

whereas presumably the desired output is:

julia> [Day(1) - Day(2), Day(1) - Day(3)]
2-element Array{Base.Dates.Day,1}:
 -1 day 
 -2 days

Looking at dates/periods.jl, the first two method definitions here work fine for + but not -:

for op in (:.+, :.-)
op_ = symbol(string(op)[2:end])
    @eval begin
        ($op){P<:Period}(x::P,Y::StridedArray{P}) = ($op)(Y,x)
        ($op_){P<:Period}(x::P,Y::StridedArray{P}) = ($op)(Y,x)
        ($op_){P<:Period}(Y::StridedArray{P},x::P) = ($op)(Y,x)
    end
end

One option might be to implement unary addition (as identity) and then do

for op in (:.+, :.-)
op_ = symbol(string(op)[2:end])
    @eval begin
        ($op){P<:Period}(x::P,Y::StridedArray{P}) = ($op_)(($op)(Y,x))
        ($op_){P<:Period}(x::P,Y::StridedArray{P}) = ($op_)(($op)(Y,x))
        ($op_){P<:Period}(Y::StridedArray{P},x::P) = ($op)(Y,x)
    end
end

or, just hardcode the definitions as

(.+){P<:Period}(x::P,Y::StridedArray{P}) = Y .+ x
(+){P<:Period}(x::P,Y::StridedArray{P}) = Y .+ x
(+){P<:Period}(Y::StridedArray{P},x::P) = Y .+ x
(.-){P<:Period}(x::P,Y::StridedArray{P}) = (-Y) .+ x
(-){P<:Period}(x::P,Y::StridedArray{P}) = (-Y) .+ x
(-){P<:Period}(Y::StridedArray{P},x::P) = Y .- x

which would actually be fewer LOC... maybe more readable too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions