title: What's a good, non-recursive algorithm to calculate a Cartesian product?
body: <h3>Note</h3>
  
  <p>This is not a REBOL-specific question. You can answer it in any language.</p>
  
  <h3>Background</h3>
  
  <p>The <a href="http://www.rebol.com" rel="nofollow noreferrer">REBOL</a> language supports the creation of domain-specific languages known as "dialects" in REBOL <em>parlance</em>. I've created such a dialect for list comprehensions, which aren't natively supported in REBOL.</p>
  
  <p>A good cartesian product algorithm is needed for list comprehensions.</p>
  
  <h3>The Problem</h3>
  
  <p>I've used meta-programming to solve this, by dynamically creating and then executing a sequence of nested <code>foreach</code> statements. It works beautifully. However, because it's dynamic, the code is not very readable. REBOL doesn't do recursion well. It rapidly runs out of stack space and crashes. So a recursive solution is out of the question.</p>
  
  <p>In sum, I want to replace my meta-programming with a readable, non-recursive, "inline" algorithm, if possible. The solution can be in any language, as long as I can reproduce it in REBOL. (I can read just about any programming language: C#, C, C++, Perl, Oz, Haskell, Erlang, whatever.)</p>
  
  <p>I should stress that this algorithm needs to support an arbitrary number of sets to be "joined", since list comprehension can involve any number of sets.</p>