From edd130626491b4a57ae9a1937b254acacb25a0c2 Mon Sep 17 00:00:00 2001 From: Curtis Vogt Date: Thu, 30 Nov 2017 19:05:36 -0600 Subject: [PATCH] Support one and oneunit (#59) * Support one and oneunit * Handle StackOverflow error with Any --- src/Missings.jl | 10 +++++++--- test/runtests.jl | 16 +++++++++++++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/Missings.jl b/src/Missings.jl index 97eacac..e1613e7 100644 --- a/src/Missings.jl +++ b/src/Missings.jl @@ -83,7 +83,7 @@ if VERSION < v"0.7.0-DEV.300" end # Unary operators/functions -for f in (:(!), :(+), :(-), :(Base.identity), :(Base.zero), +for f in (:(!), :(+), :(-), :(Base.identity), :(Base.zero), :(Base.one), :(Base.oneunit), :(Base.abs), :(Base.abs2), :(Base.sign), :(Base.acos), :(Base.acosh), :(Base.asin), :(Base.asinh), :(Base.atan), :(Base.atanh), :(Base.sin), :(Base.sinh), :(Base.cos), :(Base.cosh), :(Base.tan), :(Base.tanh), @@ -95,8 +95,12 @@ for f in (:(!), :(+), :(-), :(Base.identity), :(Base.zero), @eval $(f)(d::Missing) = missing end -Base.zero(::Type{Union{T, Missing}}) where {T <: Number} = zero(T) -Base.zero(::Type{Union{T, Missing}}) where {T <: Compat.Dates.Period} = zero(T) +for f in (:(Base.zero), :(Base.one), :(Base.oneunit)) + @eval function $(f)(::Type{Union{T, Missing}}) where T + T === Any && throw(MethodError($f, (Any,))) + $f(T) + end +end # Binary operators/functions for f in (:(+), :(-), :(*), :(/), :(^), diff --git a/test/runtests.jl b/test/runtests.jl index b9eef59..fe082c6 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -28,7 +28,7 @@ using Base.Test, Missings, Compat conj, cos, cosh, tan, tanh, exp, exp2, expm1, log, log10, log1p, log2, exponent, sqrt, gamma, lgamma, - identity, zero, + identity, zero, one, oneunit, iseven, isodd, ispow2, isfinite, isinf, isnan, iszero, isinteger, isreal, isimag, @@ -55,14 +55,24 @@ using Base.Test, Missings, Compat @test_throws MissingException f(Int, missing) end - @test zero(Union{Int, Missing}) === 0 - @test zero(Union{Float64, Missing}) === 0.0 + for T in (Int, Float64) + @test zero(Union{T, Missing}) === T(0) + @test one(Union{T, Missing}) === T(1) + @test oneunit(Union{T, Missing}) === T(1) + end for T in (subtypes(Compat.Dates.DatePeriod)..., subtypes(Compat.Dates.TimePeriod)...) @test zero(Union{T, Missing}) === T(0) + @test one(Union{T, Missing}) === 1 + @test oneunit(Union{T, Missing}) === T(1) end + # Make sure we didn't introduce a StackOverflow error + @test_throws MethodError zero(Any) + @test_throws MethodError one(Any) + @test_throws MethodError oneunit(Any) + # Comparison operators @test (missing == missing) === missing @test (1 == missing) === missing