3

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)

niczky12
  • 4,953
  • 1
  • 24
  • 34
Picaud Vincent
  • 10,518
  • 5
  • 31
  • 70
  • You might find the alternative explanation at: https://docs.julialang.org/en/stable/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1 helpful — it describes it in terms of behavior instead of implementation. – mbauman Mar 22 '18 at 21:09
  • @MattB. thanks for the link – Picaud Vincent Mar 22 '18 at 21:30

1 Answers1

1

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.

Alex338207
  • 1,825
  • 12
  • 16
  • It might be worth adding an example of how to do the above with `while` loop just for future reference? – niczky12 Mar 23 '18 at 20:17