Cartesian product of two or more lists: Difference between revisions
Content added Content deleted
m (→{{header|Tailspin}}: update syntax) |
|||
Line 1,994: | Line 1,994: | ||
ReadChar |
ReadChar |
||
END CartesianProduct.</lang> |
END CartesianProduct.</lang> |
||
=={{header|Nim}}== |
|||
To compute the product of two lists (Nim arrays or sequences), we use an iterator. Obtaining a sequence from an iterator is easily done using "toSeq" from the module “sequtils” of the standard library. |
|||
The procedure allows to mix sequences of different types, for instance integers and characters. |
|||
In order to display the result using mathematical formalism, we have created a special procedure “$$” for the sequences and have overloaded the procedure “$” for tuples. |
|||
<lang Nim>iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] = |
|||
# Yield the element of the cartesian product of "a" and "b". |
|||
# Yield tuples rather than arrays as it allows T1 and T2 to be different. |
|||
for x in a: |
|||
for y in b: |
|||
yield (x, y) |
|||
#——————————————————————————————————————————————————————————————————————————————————————————————————— |
|||
when isMainModule: |
|||
from seqUtils import toSeq |
|||
import strformat |
|||
from strutils import addSep |
|||
#------------------------------------------------------------------------------------------------- |
|||
proc `$`[T1, T2](t: tuple[a: T1, b: T2]): string = |
|||
## Overloading of `$` to display a tuple without the field names. |
|||
&"({t.a}, {t.b})" |
|||
proc `$$`[T](s: seq[T]): string = |
|||
## New operator to display a sequence using mathematical set notation. |
|||
result = "{" |
|||
for item in s: |
|||
result.addSep(", ", 1) |
|||
result.add($item) |
|||
result.add('}') |
|||
#------------------------------------------------------------------------------------------------- |
|||
const Empty = newSeq[int]() # Empty list of "int". |
|||
for (a, b) in [(@[1, 2], @[3, 4]), |
|||
(@[3, 4], @[1, 2]), |
|||
(@[1, 2], Empty ), |
|||
( Empty, @[1, 2])]: |
|||
echo &"{$$a} x {$$b} = {$$toSeq(product(a, b))}"</lang> |
|||
{{out}} |
|||
<pre>1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} |
|||
{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} |
|||
{1, 2} x {} = {} |
|||
{} x {1, 2} = {}</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |