11

Let's say I have a procedure getTuple(): (int, int, int). How do I iterate over the returned tuple? It doesn't look like items is defined for tuple, so I can't do for i in getTuple().

I initially had this returning a sequence, which proved to be a bottleneck. Can I get this to work without affecting performance? I guess as a last resort I could unroll my loop, but is there any way around that?

Imran
  • 12,950
  • 8
  • 64
  • 79

2 Answers2

10

OK, I figured this out. You can iterate over the tuple's fields:

let t = (2,4,6)

for x in t.fields:
  echo(x)
Imran
  • 12,950
  • 8
  • 64
  • 79
3

I initially had this returning a sequence, which proved to be a bottleneck. Can I get this to work without affecting performance?

Use an array[N, int] instead, it has no indirection. Why was the seq not performant enough? You might want to allocate it to correct size with newSeq[int](size) initially.

def-
  • 5,275
  • 20
  • 18
  • My sequence was allocated correctly, but profiling showed lots of time spent calling `newSeq`. This was in the innermost loop of some performance-critical simulation code. I just tested `array[N, int]` and it's vastly superior - Thanks! – Imran Feb 13 '18 at 09:29
  • 1
    Of course in an inner loop you wouldn't want to allocate seqs. Instead of copying the resulting array you could also pass in a pointer and write to the correct location directly. – def- Feb 13 '18 at 11:16