Cartesian product of two or more lists: Difference between revisions

add Tailspin solution
(→‎Functional JS: n-Ary version - a simpler and more maintainable foldr (using reduceRight))
(add Tailspin solution)
Line 3,180:
[[1, 30, 500], [1, 30, 100], [2, 30, 500], [2, 30, 100], [3, 30, 500], [3, 30, 100]]
[]</pre>
 
=={{header|Tailspin}}==
<lang tailspin>
templates cartesianProduct
{ product: [$(1)... -> [$]], rest: $(2..-1) } -> #
<{ rest: <[](0)> }> $.product !
<> def m: $.rest(1);
{ product: [$.product... -> (def n: $; $m... -> [$n..., $] !)], rest: $.rest(2..-1) } -> #
end cartesianProduct
 
'{1,2}x{3,4} = $:[[1,2],[3,4]] -> cartesianProduct;
' -> !OUT::write
 
'{3,4}x{1,2} = $:[[3,4],[1,2]] -> cartesianProduct;
' -> !OUT::write
 
'{1,2}x{} = $:[[1,2],[]] -> cartesianProduct;
' -> !OUT::write
 
'{}x{1,2} = $:[[],[1,2]] -> cartesianProduct;
' -> !OUT::write
 
'{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} = $:[[1776, 1789], [7, 12], [4, 14, 23], [0, 1]] -> cartesianProduct;
' -> !OUT::write
 
'{1, 2, 3} × {30} × {500, 100} = $:[[1, 2, 3], [30], [500, 100]] -> cartesianProduct;
' -> !OUT::write
 
'{1, 2, 3} × {} × {500, 100} = $:[[1, 2, 3], [], [500, 100]] -> cartesianProduct;
' -> !OUT::write
</lang>
{{out}}
<pre>
{1,2}x{3,4} = [[1, 3], [1, 4], [2, 3], [2, 4]]
{3,4}x{1,2} = [[3, 1], [3, 2], [4, 1], [4, 2]]
{1,2}x{} = []
{}x{1,2} = []
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} = [[1776, 7, 4, 0], [1776, 7, 4, 1], [1776, 7, 14, 0], [1776, 7, 14, 1], [1776, 7, 23, 0], [1776, 7, 23, 1], [1776, 12, 4, 0], [1776, 12, 4, 1], [1776, 12, 14, 0], [1776, 12, 14, 1], [1776, 12, 23, 0], [1776, 12, 23, 1], [1789, 7, 4, 0], [1789, 7, 4, 1], [1789, 7, 14, 0], [1789, 7, 14, 1], [1789, 7, 23, 0], [1789, 7, 23, 1], [1789, 12, 4, 0], [1789, 12, 4, 1], [1789, 12, 14, 0], [1789, 12, 14, 1], [1789, 12, 23, 0], [1789, 12, 23, 1]]
{1, 2, 3} × {30} × {500, 100} = [[1, 30, 500], [1, 30, 100], [2, 30, 500], [2, 30, 100], [3, 30, 500], [3, 30, 100]]
{1, 2, 3} × {} × {500, 100} = []
</pre>
 
=={{header|Tcl}}==
Anonymous user