proc pt*[N:SomeNumber](x, y, z:N):tuple[x,y,z:float] =
return (x: x.float, y: y.float, z: z.float)
let t1 = pt(0,0,0)
let t2 = pt(0.1, 0, 0)
let t3 = pt(0.1, 0.3, 0)
let t4 = pt(0, 0.3, 0) #<----- Why is this failing?
echo t1
echo t2
echo t3
echo t4
gives the following error:
/tmp/ex01.nim(7, 12) Error: type mismatch: got <int literal(0), float64, int literal(0)> but expected one of: proc pt[N: SomeNumber](x, y, z: N): tuple[x, y, z: float] first type mismatch at position: 2 required type for y: N: SomeNumber but expression '0.3' is of type: float64 expression: pt(0, 0.3, 0)
Why?
Your pt proc is a generic proc, that is when you call it with different types, then for each type an instance is created.
For t1 you call it with int arguments, so an instance for ints is created.
For t2 and t3 first argument is a float, so a float instance is created, the other literals are passed as float too.
For t4 first arg is a int literal, so the already existing int instance is used, but second arg if of type float, which is not automatically converted to int, so the compile error.
Hope that is right.
@Stefan_Salewski is right
Change to that
proc pt*[N:SomeNumber](x, y, z:N):tuple[x,y,z:float] =
return (x: x.float, y: y.float, z: z.float)
let t1 = pt(0,0,0)
let t2 = pt(0.1, 0, 0)
let t3 = pt(0.1, 0.3, 0)
let t4 = pt(0.0, 0.3, 0) #<-----
echo t1
echo t2
echo t3
echo t4
Or that
proc pt*(x, y, z:float):tuple[x,y,z:float] =
# ^^^^^
return (x: x.float, y: y.float, z: z.float)
let t1 = pt(0,0,0)
let t2 = pt(0.1, 0, 0)
let t3 = pt(0.1, 0.3, 0)
let t4 = pt(0, 0.3, 0) #<-----
echo t1
echo t2
echo t3
echo t4
Thanks Stefan. Understood.
I fixed it with:
proc pt*[N1,N2,N3:SomeNumber](x:N1, y:N2, z:N3):tuple[x,y,z:float] =