I am trying to keep a function generic with regard to its integer arguments. One of the function portions is
if n > typemax(T) ÷ k
break
end
and since T is Integer and could be BigInt, I would like a suggestion what to do about
julia> typemax(BigInt)
ERROR: MethodError: no method matching typemax(::Type{BigInt})
There are at least two approaches. One will be more appropriate. To write the function so BigInts are not accepted but all other built-in Integer types (or so all other built-in Signed Integer types) are accepted:
function for_builtin_fixedsize_integers(x::Base.BitInteger) ...
function for_builtin_fixedsuze_signedintegers(x::Base.BitSigned) ...
To accept BigInts and avoid the error that typemax(BigInt)
triggers
(a) rewrite your function so typemax(T)
is not used
or
(b) rewrite your function so typemax(BigInt)
is avoided
consider using
const MaxBigInt = # whatever you choose
function avoids_error(x) # or (x::Signed) or (x::Integer)
# code
maxint = x isa BigInt ? MaxBigInt : typemax(typeof(x))
# code
end
or an approach similar to
function avoids_error(x) # or (x::Signed) or (x::Integer)
# code
maxint = x isa BigInt ? x^2: typemax(typeof(x))
# code
end
You can use the Base.hastypemax
trait, in order to conditionally make a check only for bounded integer types, e.g.
if hastypemax(T) && n > typemax(T) ÷ k
break
end
Note that Base.hastypemax
is currently not public API, there is an issue on this: Rational of `Base.hastypemax(BigInt)` (not exported) vs `typemax(BigInt) = Inf` · Issue #39344 · JuliaLang/julia · GitHub.
3 Likes