Taking cross products of two or more lists

I input a list of lists in a function called cross_product(list_of_list) and it returns a list of cross products.
I can use for if I know the number of lists passed in the list but what to do if we don’t know how many lists are passed and we have to take the cross product of these lists.

here is an example list

[
 [[1, 2], [3, 4]], 
 [[4, 5], [6, 7]]
]

the output should be

[ 
 [1, 2, 4, 5], [1, 2, 6, 7], [3, 4, 4, 5], [3, 4, 6, 7]
]

You’ll need recursion for that:

defmodule A do
    def cross([hd]), do: hd

    def cross([hd | tail]) do
        for a <- hd, b <- Enum.map(cross(tail), fn b -> a ++ b end) do
            b
        end
    end
end
3 Likes

thanks a lot