Need help implementing evenness test for larger integer types

After taking advice from this thread (10%) and LLaMa (90%), I decided to leverage the power of multiple dispatch to work around the parser’s recursion issue with large expressions:

even(x) = even(Val(x))

let T = UInt16
  for value in typemin(T):typemax(T)
    @eval even(x::Val{$value}) = $(iseven(value))
  end
end

It runs fine:

julia> join([even(UInt16(i)) for i in 0:9], ", ") # comprehensive unit test
"true, false, true, false, true, false, true, false, true, false"

julia> @time [even(UInt16(i)) for i in 0:60000]; # peak performance
  0.112477 seconds (92.46 k allocations: 2.628 MiB, 33.53% compilation time)

Just don’t check even or methods(even) in the REPL because that’ll hang for 3 minutes before possibly printing thousands of methods for another minute, and just for UInt16. Time to toss this into another loop over integer values and precompile it in a package. I’ll just throw in a #TODO Val{x::BigInt} for the next contributor.

3 Likes