Can any kind fellow explain why?
proc addit[T, U] (a: T, b: U): auto =
return a + b
proc main() =
#echo addit(12, 22.1) #<-- won't work
echo(12 + 22.1)
main()
I'm not 100% sure but I'll note that removing the type parameters such as:
proc addit(a: int, b: float): auto =
return a + b
still doesn't compile, it triggers the same type mismatch error due to the unavailability of a suitable + proc. So the reason isn't related to using type parameters.
I would venture that it has to do with Nim's sophisticated compile-time evaluator which may reduce the expression (12 + 22.1) to (34.1) before proc dispatch resolution happens.
The way to go:
type Addable = concept x, y
x + y
proc addit(a, b: Addable): auto =
return a + b
echo addit(12, 22.1) # -> 34.1
echo addit({1,3,5},{5,7}) # -> {1,3,5,7}
Yet you can explicitly convert arguments, this way you decide by yourself what type is the result:
proc additF[T, U] (a: T, b: U): auto =
return a.float + b.float
proc additI[T, U] (a: T, b: U): auto =
return a.int + b.int
echo additF(12, 22.1) # -> 34.1
echo additI(12, 22.1) # -> 34
Yet you can use implicit conversion:
proc addit[T, U] (a: T, b: U): auto =
return a + b
converter x(x: int): float = x.float
echo addit(12, 22.1) # -> 34.1
But it can make the code's logic more messy.
Below "submit" button there's a hint on making your code sample syntax-highlighted, makes reading easier.