title: What's a good way to structure variable nested loops?
body: <p>Suppose you're working in a language with variable length arrays (e.g. with <code>A[i]</code> for all <code>i</code> in <code>1..A.length</code>) and have to write a routine that takes <code>n</code> (<code>n : 1..8</code>) variable length arrays of items in a variable length array of length <code>n</code>, and needs to call a procedure with every possible length <code>n</code> array of items where the first is chosen from the first array, the second is chosen from the second array, and so forth.  </p>
  
  <p>If you want something concrete to visualize, imagine that your routine has to take data like:</p>
  
  <pre><code>[ [ 'top hat', 'bowler', 'derby' ], [ 'bow tie', 'cravat', 'ascot', 'bolo'] ... ['jackboots','galoshes','sneakers','slippers']]
  </code></pre>
  
  <p>and make the following procedure calls (in any order):</p>
  
  <pre><code>try_on ['top hat', 'bow tie', ... 'jackboots']
  try_on ['top hat', 'bow tie', ... 'galoshes']
   :
  try_on ['derby','bolo',...'slippers']
  </code></pre>
  
  <p>This is sometimes called a chinese menu problem, and for fixed <code>n</code> can be coded quite simply (e.g. for <code>n</code> = 3, in pseudo code)</p>
  
  <pre><code>procedure register_combination( items : array [1..3] of vararray of An_item)
      for each i1 from items[1]
          for each i2 from items[2]
              for each i3 from items[3]
                  register( [ii,i2,i3] )
  </code></pre>
  
  <p>But what if <code>n</code> can vary, giving a signature like:</p>
  
  <pre><code>procedure register_combination( items : vararray of vararray of An_item)
  </code></pre>
  
  <p>The code as written contained an ugly case statement, which I replaced with a much simpler solution.  But I'm not sure it's the best (and it's surely not the only) way to refactor this.</p>
  
  <p>How would you do it?  Clever and surprising are good, but clear and maintainable are better--I'm just passing through this code and don't want to get called back.  Concise, clear <em>and</em> clever would be ideal.</p>
  
  <p>Edit: I'll post my solution later today, after others have had a chance to respond.</p>
  
  <p>Teaser: I tried to sell a recursive solution, but they wouldn't go for it, so I had to stick to writing fortran in a HLL.</p>
  
  <p>The answer I went with, posted below.</p>