While working on a CSP (Constraint Satisfaction Problem)
in Elixir, I was in need to compute Cartesian product of a lists of variable
domains. Elixir being a declarative programming language, I was expecting
there to be function List.cartesian_product/1
that takes a list of
enumerables, but nothing like that existed. So, I resorted to the more
imperative list comprehension:
defmodule Cartesian do
def cartesian_product(set1, set2) do
for elem1 <- set1, elem2 <- set2 do
{elem1, elem2}
end
end
end
## Examples
iex> Cartesian.cartesian_product([1, 2], [:three, :four, :five])
[
{1, :three},
{1, :four},
{1, :five},
{2, :three},
{2, :four},
{2, :five}
]