logo

How to Use Elegant Loops in Julia 📂Julia

How to Use Elegant Loops in Julia

Guide

while

The while loop is no different from other languages.

julia> while x < 10
           x += 1
           print("▷eq1◁i - ")
       end
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 -

julia> for i = 1:10
           print("▷eq2◁i - ")
       end
1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 -

The three major looping styles used in Julia are as above. The top one is similar to the method used in R and Python, the second is similar to Matlab, and the most elegant expression is the third, which uses the Set comprehension method.

Nested Loops

The following two loops function identically.

julia> X = 1:4; Y = 8:(-1):5;

julia> for x ∈ X
           for y ∈ Y
               print("  (▷eq3◁y) = ▷eq4◁x + ▷eq5◁(x + y)")
           if y == 5 println() end
       end
  (1 + 8) = 9  (1 + 7) = 8  (1 + 6) = 7  (1 + 5) = 6
  (2 + 8) = 10  (2 + 7) = 9  (2 + 6) = 8  (2 + 5) = 7
  (3 + 8) = 11  (3 + 7) = 10  (3 + 6) = 9  (3 + 5) = 8
  (4 + 8) = 12  (4 + 7) = 11  (4 + 6) = 10  (4 + 5) = 9

It’s like writing code as if it were Pseudo Code. A note of caution is the following case where a tuple is given as an Iterator.

julia> for (x,y) ∈ (X, Y)
           print("  (▷eq3◁y) = ▷eq7◁x + ▷eq5◁(x + y)")
           if y == 5 println() end
       end
  (1 + 8) = 9  (2 + 7) = 9  (3 + 6) = 9  (4 + 5) = 9