Nim enumerate function like Python
Asked Answered
H

1

6

Learning Nim and I like it resemblence of Python (but fast). In Python I can do this:

item_index = [(idx, itm) for idx, itm in enumerate(row)]

Im looking for a way to enumerate a Nim sequence so I would write this:

item_index = lc[(idx, itm) | (idx, itm <- enumerate(row))]

Does this functionality exist? I'm sure you could create it, maybe with a proc, template or macro it but I'm still very new, and these seem hard to create myself still. Here is my attempt:

iterator enumerate[T](s: seq[T]): (int, T) =
    var i = 0
    while i < len(s):
        yield (i, s[i])
        i += 1
Helenhelena answered 5/1, 2018 at 20:20 Comment(0)
L
14

I'm a newbie with nim, and I'm not really sure what you want, but... If you use two variables in a for statement, you will get the index and the value:

for x, y in [11,22,33]:
  echo x, " ", y

Gives:

0 11
1 22
2 33

HTH.

Lastminute answered 6/1, 2018 at 0:19 Comment(3)
Some background why this works: When Nim's sees a for loop with two loop variables, it tries to call pairs on the given expression. The pairs operator is defined for openarray in system.nim and it does exactly what enumerate does.Hsining
Please note that this doesn't work for all iterables. For example, if you try to do this with start .. end or with countup(start, end, step) you will get a wrong number of variables error.Baxie
@ArthurKhazbs why would you do that?, OP is trying to iterate an array.Schock

© 2022 - 2024 — McMap. All rights reserved.