Search code examples
smlsmlnjml

Generating cartesian power in Standard ML


The common cartesian product can be implemented as:

fun cartesian(xs, ys) =
   let fun pairOne(x,[]) = []
     | pairOne(x, y::ys) = [x,y]::pairOne(x,ys)
       fun cart([],ys) = []
     | cart(x::xs, ys) = pairOne(x, ys) @ cart(xs,ys)
   in
       cart(xs,ys)
   end

I'm looking for a way to generate the cartesian power of grade k.

For k=2, this would output:

[[true,true],[true,false],[false,true],[false,false]]

And for k=3:

[[true,true,true],[true,true,false],[true,false,false],[false,false,false],[false,false,true],...]

Thanks


Solution

  • The following seems to work:

    fun product [] _ = []
    |   product (x::xs) products = (map (fn p => x::p) products) @ product xs products
    
    fun power _ 0 = []
    |   power xs 1 = map (fn x => [x]) xs
    |   power xs n = product xs (power xs (n-1))
    

    The first function forms a Cartesian product of a list and another list which is itself already a list of lists. For example,

    - product [1,2] [[3],[4]];
    val it = [[1,3],[1,4],[2,3],[2,4]] : int list list
    

    The main use of this is as a helper function which adds another factor to an existing Cartesian product. The function power first takes the list and converts it to a "power" with 1 factor in the basis case n = 1 and then subsequently builds up the power using the recursion A^n = A x A^(n-1).

    For example,

    - power [true,false] 2;
    val it = [[true,true],[true,false],[false,true],[false,false]] : bool list list