Task

Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.

Demonstrate that your function/method correctly returns:

{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:

{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.

 {1, 2} × {} = {}
 {} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.

Use your n-ary Cartesian product function to show the following products:

 {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
 {1, 2, 3} × {30} × {500, 100}
 {1, 2, 3} × {} × {500, 100}


MODULE CartesianProduct;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
PROCEDURE WriteInt(a : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
    FormatString("%i", buf, a);
    WriteString(buf)
END WriteInt;
 
PROCEDURE Cartesian(a,b : ARRAY OF INTEGER);
VAR i,j : CARDINAL;
BEGIN
    WriteString("[");
    FOR i:=0 TO HIGH(a) DO
        FOR j:=0 TO HIGH(b) DO
            IF (i>0) OR (j>0) THEN
                WriteString(",");
            END;
            WriteString("[");
            WriteInt(a[i]);
            WriteString(",");
            WriteInt(b[j]);
            WriteString("]")
        END
    END;
    WriteString("]");
    WriteLn
END Cartesian;
 
TYPE
    AP = ARRAY[0..1] OF INTEGER;
    E = ARRAY[0..0] OF INTEGER;
VAR
    a,b : AP;
BEGIN
    a := AP{1,2};
    b := AP{3,4};
    Cartesian(a,b);
 
    a := AP{3,4};
    b := AP{1,2};
    Cartesian(a,b);
 
    (* If there is a way to create an empty array, I do not know of it *)
 
    ReadChar
END CartesianProduct.