diff --git a/src/HalfIntegers.jl b/src/HalfIntegers.jl index 0c1b427..2be62af 100644 --- a/src/HalfIntegers.jl +++ b/src/HalfIntegers.jl @@ -50,7 +50,7 @@ HalfInteger(x::BigFloat) = BigHalfInt(x) if isinteger(x) Base.unsafe_rational(tx >> 1, one(tx)) else - Base.unsafe_rational(tx, oftype(tx, 2)) + Base.unsafe_rational(tx, twice(one(tx))) end end function (::Type{Rational{T}})(x::HalfInteger) where T @@ -58,11 +58,11 @@ HalfInteger(x::BigFloat) = BigHalfInt(x) if isinteger(x) Base.unsafe_rational(T, tx >> 1, one(tx)) else - Base.unsafe_rational(T, tx, oftype(tx,2)) + Base.unsafe_rational(T, tx, twice(one(tx))) end end else - (T::Type{<:Rational})(x::HalfInteger) = (tx=twice(x); T(tx,oftype(tx,2))) + (T::Type{<:Rational})(x::HalfInteger) = (tx=twice(x); T(tx,twice(one(tx)))) end Base.ArithmeticStyle(::Type{<:HalfInteger}) = Base.ArithmeticWraps() diff --git a/test/customtypes.jl b/test/customtypes.jl index 6b19cd4..847a0dc 100644 --- a/test/customtypes.jl +++ b/test/customtypes.jl @@ -9,6 +9,13 @@ MyHalfInt(x::MyHalfInt) = x HalfIntegers.half(::Type{MyHalfInt}, x) = MyHalfInt(half(HalfInt, x)) HalfIntegers.twice(x::MyHalfInt) = twice(x.val) +struct One <: Integer end +Base.promote_rule(::Type{One}, ::Type{T}) where {T<:Number} = promote_type(Bool, T) +Base.Int(::One) = 1 +Base.iseven(::One) = false +Base.one(::One) = One() +Base.:+(x::One, y::One) = 2 + @testset "Custom types" begin @testset "Construction" begin @test MyHalfInt(2.5) isa MyHalfInt @@ -35,6 +42,9 @@ HalfIntegers.twice(x::MyHalfInt) = twice(x.val) @test_throws InexactError Integer(MyHalfInt(3/2)) @test_throws InexactError Int(MyHalfInt(3/2)) @test_throws InexactError UInt(MyHalfInt(-1)) + + @test Rational(half(One())) == 1//2 + @test Rational{Int}(half(One())) == 1//2 end @testset "Properties" begin