Picaud Vincent
Picaud Vincent

Reputation: 10982

Modifying the counter in a for-loop

I was surprised by this behavior (in Julia)

for i in 1:10
  println(i)
  i=i+4
end

prints:

1
2
...
9
10

(modification of i in the loop body is not taken into account)

In C/C++

for(int i=1;i<=10;i++) {
  std::cout << "\n" << i;
  i+=4;
}

you would get:

1
6

Reading Julia doc:iteration, I realized that the for loop

for i = I   # or  "for i in I"
    # body
end

is certainly transformed into:

state = start(I)
while !done(I, state)
    (i, state) = next(I, state)
    # body
end

In that case we understand that i modifications are not taken into account. Everything depends on the state variable.

Question1: am I right with this explanation?

Question2: the state variable seems to be inaccessible/hidden to the user. By consequence, construction like

for i in 1:10
  println(i)
  i=i+4
end

with a for loop seems impossible. Is it correct?

(I know that I can use a while i<=n loop)

Upvotes: 3

Views: 457

Answers (1)

Alex338207
Alex338207

Reputation: 1905

Question 1: yes, and it is in fact the same as in python:

for i in range(10):
   print(i)
   i=i+4

Outputs 0,1,2,...9.

Several concepts in julia's have been influenced by python. Here is an explanation of python iterator:

Julia's start, next, done are equivalent to Pythons __iter__ method, next and raising the StopIteration exception.

Question 2: The variable state is indeed not accessible if a loop is start with for i in 1:3.

Upvotes: 1

Related Questions