Generate nested for loops using metaprogramming?

question
metaprogramming

#1

Given a set of characters and a number I’m trying to generate all possible sequences. For example, given
"ACTG" to generate all possible sequences of length 2 I could do.

letters = "ACTG"

for i in letters
    for j in letters
        print(i,j," ")   
    end
end

AA AC AT AG CA CC CT CG TA TC TT TG GA GC GT GG 

And say n = 3 I could do

for i in letters
    for j in letters
        for k in letters        
            print(i,j,k," ")  
        end
    end
end

My question is how can I do this with Julia’s metaprogramming?


#2

Check out @nloops: https://docs.julialang.org/en/release-0.6/devdocs/cartesian/#Base.Cartesian-1


#3

Although if you’re actually just trying to generate a product of sequences, then Iterators.product will be easier:

julia> for (i, j) in Iterators.product("ACTG", "ACTG")
         print(i, j, " ")
       end
AA CA TA GA AC CC TC GC AT CT TT GT AG CG TG GG

#4

Thanks, that’s way simpler. I’ll have a go at solving it with @nloops for the fun anyways.


#5

Half a year later I did it lol.

function permutations(array,n)
    exp = quote
        l = []
        @nloops $n i _ -> 1:length($array) begin
            idx =[@ntuple($n,i)...]
            push!(l,$array[idx])
        end
        l
    end
    eval(exp)
end