I’m writing a function where I want to use Base.Cartesian.@nloops
to collect possible combinations of inputs, but the object I am creating has one index with a fixed value. Here is a function that does something similar to what I’m after:
using Base.Cartesian: @nloops, @ntuple
function looptest(i)
@nloops 3 d _ -> (true, false) begin
println(@ntuple 3 k -> k == i ? 2 : d_k ? 0 : 1)
end
end
The function creates a 3-element tuple, but one of the three elements has a fixed value that does not vary through the loops. The output looks like this:
julia> looptest(2)
(0, 2, 0)
(1, 2, 0)
(0, 2, 0)
(1, 2, 0)
(0, 2, 1)
(1, 2, 1)
(0, 2, 1)
(1, 2, 1)
I would like to end up with something that does not duplicate each tuple:
julia> looptest(2)
(0, 2, 0)
(1, 2, 0)
(0, 2, 1)
(1, 2, 1)
I’ve hit a wall in trying to work out how to do this using the tools in Base.Cartesian
. I thought initially I could reduce the number of loops by 1:
function looptest(i)
@nloops 2 d _ -> (true, false) begin
println(@ntuple 3 k -> k == i ? 2 : d_k ? 0 : 1)
end
end
But then d_3
is not defined. If I could somehow interpolate the fixed index i
, a condition would ensure each tuple is only created once. The desired interpolation would be something like this:
function looptest(i)
@nloops 3 d _ -> (true, false) begin
if d_$i
println(@ntuple 3 k -> k == i ? 2 : d_k ? 0 : 1)
end
end
end
But this throws ERROR: LoadError: syntax: "$" expression outside quote around ...
. I’ve searched around for a bit and can’t figure out how to get an interpolation like this to work.
Is there some way I can combine @nloops
and @ntuple
to get the desired result? Or is there an alternative approach that would work better? Any direction would be much appreciated!
Background: I’m writing a function to compute the vertices of a KDTree
from NearestNeighbors.jl. I’ve written a function using the above approach that works for a given HyperRectangle
, but I want to extend it to compute only the new vertices created by child nodes. The fixed index is the KDNode.split_dim
.