Hi,
Recently I was surprised that a function can take tuple as a parameter, so I started to play with it. It might generate several functions in C like when I use generics. Is there any other hidden logic to use generics?
More details:
If I create a test function with generics and call it with two different type of parameters:
proc test[T](x: T): T =
result = 10 + x
echo test(1) # prints 11
echo test(2) # prints 12
echo test(3.0) # prints 13.0
then the C code will contain two instances: one for int and one for float. Everything is clear.
Then I know about templates and macros. The previous example with template:
template testTemplate(x: expr): expr =
10 + x
echo testTemplate(1) # prints 11
echo testTemplate(2) # prints 12
echo testTemplate(3.0) # prints 13.0
All the 3 cases the code is replaced by the template (the compiler is smart enough to calculate the result, no addition at runtime). I understand this.
So I was surprised to see this (thanks again def, you showed this to me):
proc myPrint(xs: tuple): string =
result = "("
for x in xs.fields:
if result.len > 1:
result.add(", ")
result.add($x)
result.add(")")
echo myPrint((1,2)) # prints (1, 2)
echo myPrint((3,4)) # prints (3, 4)
echo myPrint(("A","B","C")) # prints (A, B, C)
This function takes a tuple as parameter, and in this case generates a function which takes (int, int), and a function which takes (string, string, string). Moreover, the for cycle is unwrapped by the compiler. I like this, but this feels like black magic. Is there somewhere more info about this? What else can I do like this (e.g. proc, seq, array)?
Thank you, Peter