How to create a @ntuple-like macro but can hundle arbitrary number of nested loops

I would like to create a macro that can hundle arbitrary number of nested loops:

julia> @ntuple 3 i -> 2i
(2, 4, 6)

julia> FEM.@ntuple 2 3 (i,j) -> (2i,j)
((2, 1), (4, 1), (2, 2), (4, 2), (2, 3), (4, 3))

Is there anyway to to this?

There are macros that do that in Base Julia, but you can probably avoid them by reading this blog post: https://julialang.org/blog/2016/02/iteration/

Thank you for your reply! But Base Julia cannot do the later example but only the first one.

It can actually, and depending on what exactly you’re trying to do… it still probably can.

Using CartesianIndices, which I think is the main takeaway of that blog post, is extremely powerful. I’ve gotten used to using it in the context of combinatorics (often things “look” like multidimensional array indices even when they’re not), and it’s always amazed me how far that can take you.

If that doesn’t do the trick, a macro for N-loops already exists. Base.@nloops will no doubt do what you want, it just might be the wrong tool for most cases.

2 Likes