Cartesian product of two or more lists: Difference between revisions

Content added Content deleted
(Realize in F#)
Line 439: Line 439:
{(1, 30, 500), (1, 30, 100), (2, 30, 500), (2, 30, 100), (3, 30, 500), (3, 30, 100)}
{(1, 30, 500), (1, 30, 100), (2, 30, 500), (2, 30, 100), (3, 30, 500), (3, 30, 100)}
</pre>
</pre>

=={{header|Common Lisp}}==
<lang lisp>(defun cartesian-product (l)
"Compute the n-cartesian product of a list of sets represented as list with a mixed recursive-iterative approach.
Algorithm:
If there are no sets, then produce an empty set of tuples;
otherwise, for all the elements x of the first set, concatenate the sets obtained by
inserting x at the beginning of each tuple of the n-cartesian product of the remaining sets."
(if (null l)
(list nil)
(loop for x in (car l)
nconc (loop for y in (cartesian-product (cdr l))
collect (cons x y)))))</lang>

Example of use:

<lang lisp>CL-USER> (cartesian-product '((1 2 3) (30) (500 100)))
((1 30 500) (1 30 100) (2 30 500) (2 30 100) (3 30 500) (3 30 100))
</lang>


=={{header|D}}==
=={{header|D}}==