Too many levels of nested for loops

Is there a more pretty way to rewrite the code below, without performance penalties?

sum = 0
for i1 in 1:4
    for i2 in 1:4
        for i3 in 1:4
            for i4 in 1:4
                sum += some_function(i1, i2, i3, i4)
            end
        end
    end
end

My actual code has even more levels (six) of nesting. This big triangle shape is an eyesore!

julia> s = 0
       for i1=1:4, i2=1:4, i3=1:4, i4=1:4
          s += i1 + i2 + i3 + i4
       end
       s
2560

julia> s = 0
       for i1 in 1:4,
           i2 in 1:4,
           i3 in 1:4,
           i4 in 1:4
         s += i1 + i2 + i3 + i4
       end
       s
 2560
5 Likes

If you need even more power (i.e., do this nested loop over an array of ranges instead of a fixed number of them) you probably can use Combinatorics.jl.

5 Likes

you can use Iterators.product:

s = 0
for (i1,i2,i3,i4) in Iterators.product(1:4, 1:4, 1:4, 1:4)
    s += i1 + i2 + i3 + i4
end
s

or with an arbitrary number of nested loops:

N = 4
s = 0
for i in Iterators.product(fill(1:4, N)...)
    s += sum(i)
end
s
8 Likes