Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for Int32 literals in Julia

Tags:

julia

int32

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?

like image 743
Corylus Avatar asked Oct 15 '25 04:10

Corylus


1 Answers

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
like image 120
ahnlabb Avatar answered Oct 18 '25 21:10

ahnlabb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!