I have a problem with writing a Cartesian power function. I found many examples about calculating Cartesian Product, but no one about Cartesian power.
For example, [1;2] raised to power 3 = [ [1;1;1] ; [1;1;2] ; [1;2;1] ; [1;2;2] ; [2;1;1] ; [2;1;2] ; [2;2;1]; [2;2;2] ]
I use following code to calculate Cartesian Product:
let Cprod U V =
let mutable res = []
for u in U do
for v in V do
res <- res @ [[u;v]]
res
And trying to calculate Cartesian power.
I use following code to calculate Cartesian Product:
let Cpower U n =
let mutable V = U
for i=0 to n-1 do
V <- Dprod U V
V
Visual Studio said: Error The resulting type would be infinite when unifying ”a’ and ”a list’. I will thankful for any help and links.
I would also add that it is generally prefered to avoid using
mutablevalues when writing F# code. It’s fine when you’re learning F# or when you need to optimize some code to run faster, but if you want to write a more idiomatic F# code, it’s better to use recursion instead ofmutablevalues.I tried to write the Cartesian power a bit more elegantly and here is my version. It is implemented recursively. I explicitly handle the case when we need to calculate
X^1and the recursive case performs a Cartesian product like this:X^n = X * X^(n-1)I’m using sequence expressions and the method generates elements of the sequence (to be returned as the result) using
yield:This isn’t the most efficient implementation (e.g. because using
yieldinsideforloop may not be a good thing to do), but that would be only problem for largen. In F#, it is usually a good idea to start with the cleanest implementation that’s easier to understand :-).