Imran
Imran

Reputation: 13468

How to iterate over a tuple in Nim?

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?

Upvotes: 12

Views: 1606

Answers (2)

def-
def-

Reputation: 5403

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.

Upvotes: 3

Imran
Imran

Reputation: 13468

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)

Upvotes: 11

Related Questions