I wonder whether integers work in Nim as most people would expect.
Is anybody surprised by the output of the program below?
const c_1bn = 1_000_000_000
let i_4bn = 4 * c_1bn
proc test_1[T](n : T) = echo n, "A"
proc test_1[T : int|uint](n : T) = echo n, "B"
proc test_1(n : int64) = echo n, "C"
proc test_1(n : int16) = echo n, "D"
test_1(c_1bn)
test_1(2'i8)
test_1(3'u16)
test_1(i_4bn)
proc test_2[T](n : T) = echo n, "A"
proc test_2[T : int](n : T) = echo n, "B"
proc test_2(n : uint) = echo n, "C"
proc test_2(n : int16) = echo n, "D"
test_2(5_000_000_000)
test_2(6'i8)
test_2(7'u16)
proc test_3[T](n : T) = echo n, "A"
proc test_3[T : uint](n : T) = echo n, "B"
proc test_3(n : int) = echo n, "C"
proc test_3(n : int64) = echo n, "D"
test_3(8_000_000_000)
test_3(9'i8)
test_3(10'u16)
(Wrong answers: 1abcd2bcd3bcd4abcd5bcd6bcd7bcd8abc9bcd10bcd)The program doesn't compile for me:
temp2.nim(13, 7) Error: ambiguous call; both temp2.test_1(n: T: int or uint) [declared in C:Usersrumpfprojectsnimtemp2.nim(7, 6)] and temp2.test_1(n: T) [declared in C:Usersrumpfprojectsnimtemp2.nim(5, 6)] match for: (int literal(1000000000))
proc xyz[T : int](x : T) = echo x
xyz(1'i8)
xyz(1'i32)
generates two distinct procedures for int8 and int32 in the c code. How does that happen if int is not a generic type, which would be treated as a type class according to the spec?this is interesting,I was expecting that T was lifted to integer. Instead is just validated it can be used as integer but the type stays as passed from parameter.
proc xyz[T : int](x : T) =
echo "type of param is ", type(x)
echo "type of generic is ", T
echo x
xyz(1'i8)
# type of param is int8
# type of generic is int8
A little puzzler:
proc add_size[T : int](n : T) : T = n + n.sizeof.T
proc add_size(n : int16) : int16 = n + 20'i16 # Bonus !
let n_1 : int8 = 1
let n_2 : int16 = add_size(n_1)
let n_22 : int32 = add_size(n_2)
let n_26 : int = add_size(n_22)
let n_34 : int64 = add_size(n_26)
echo n_34 # output : 34 (on 64bit system)