juliaint32

Shorthand for Int32 literals in Julia


I use lots of Int32s in my code because I have some large arrays of those. But for some x::Int32 we have typeof(x+1) == Int64 since numeric literals are Int64 by default (I have to use 64bit Julia to handle my arrays). The problem is, if I have some function f(x::Int32) then f(x+1) will method error. I don't want to implement a f(x::Int64) = f(convert(Int32, x)) for almost every function and want to use concrete types for type stability. Currently, I simply have expressions like x + Int32(1) all over my code which looks really cluttered. For other types we have shorthands, i.e., 1.f0 gives me a Float32 and big"1" a BigInt. Is there something similar for Int32?


Solution

  • Since you explicitly mention the big_str macro (big"") you can easily define a similar macro for Int32 (the same way the uint128_str and int128_str is defined):

    macro i32_str(s)
        parse(Int32, s)
    end
    
    julia> typeof(i32"1")
    Int32
    

    this might still clutter your code too much so alternatively you could exploit that a number followed by a name is multiplication:

    struct i32 end
    
    (*)(n, ::Type{i32}) = Int32(n)
    
    julia> typeof(1i32)
    Int32