Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Trouble using sliced sequence inside for as iterator #321

Closed
gradha opened this Issue Jan 27, 2013 · 1 comment

Comments

Projects
None yet
2 participants
Contributor

gradha commented Jan 27, 2013

Take this simple loop:

var t1 = @["1", "2", "3", "4"]
for t in t1:
  echo repr(t)

Let's rewrite it as:

var t1 = @["1", "2", "3", "4"]
for t in t1[1..3]:
  echo repr(t)

Then you get a compiler stack trace:

Traceback (most recent call last)
nimrod.nim(82)           nimrod
nimrod.nim(56)           HandleCmdLine
main.nim(219)            MainCommand
main.nim(132)            CommandCompileToC
main.nim(98)             CompileProject
main.nim(84)             CompileModule
passes.nim(169)          processModule
passes.nim(102)          closePasses
cgen.nim(1141)           myClose
cgen.nim(1065)           finishModule
cgen.nim(724)            genProcNoForward
cgen.nim(652)            genProcAux
Error: unhandled exception: index out of bounds [EInvalidIndex]

But it compiles and runs as expected if we use a temporal variable:

var t1 = @["1", "2", "3", "4"]
let temp = t1[1..3]
for t in temp:
  echo repr(t)

As a bonus I tried python's negative notation:

var t1 = @["1", "2", "3", "4"]
let temp = t1[-1..1]
for t in temp:
  echo repr(t)

But then there is no output. I guess the compiler doesn't like that anyway, trying to reverse the indices like let temp = t1[1..-1] fails at compilation stage with:

Error: undeclared identifier: '..-'

I didn't find info about slices in the tutorial, and the manual is really sparse and doesn't mention their usage with sequences, so not sure if negative indices are meant to work or not. If not, maybe the compiler could try to give a better error message to the expectation of negative indices.

Member

fowlmouth commented Feb 2, 2013

The last error is because ..- is a valid identifier name, you want let temp = t1[1.. -1]

@Araq Araq closed this in b7c26a1 Apr 8, 2013

reactormonk pushed a commit to reactormonk/nim that referenced this issue Apr 7, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment