5

I was just thinking how Tuples was created so , I came up with this,

Flatten[Outer[List, {a, b}, {a, b}, {a, b}], 2] == Tuples[{a, b}, 3]

True

Now, I want to convert it to a function,

fun[x_List] := Block[{}, Flatten[Outer[List, x], Length[x] - 1]]

But the problem is the I need to put this List as a sequence but I am not finding a work around.

LCarvalho
  • 9,233
  • 4
  • 40
  • 96
Pankaj Sejwal
  • 2,063
  • 14
  • 23

2 Answers2

5

You can use SlotSequence and ConstantArray (or Table):

fun[x_List, n_Integer] := Flatten[Outer[List, ##] & @@ ConstantArray[x, n], 2]

fun[{a, b}, 3] == Tuples[{a, b}, 3]
(* True *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472
4

Here's an approach with Table.

fun[x_List, n_Integer] := Flatten[Outer[List, Sequence @@ Table[x, {n}]], n-1]

examples

fun[{a, b}, 3]

{{a, a, a}, {a, a, b}, {a, b, a}, {a, b, b}, {b, a, a}, {b, a, b}, {b, b, a}, {b, b, b}}


fun[{a, b}, 4]

{{a, a, a, a}, {a, a, a, b}, {a, a, b, a}, {a, a, b, b}, {a, b, a, a}, {a, b, a, b}, {a, b, b, a}, {a, b, b, b}, {b, a, a, a}, {b, a, a, b}, {b, a, b, a}, {b, a, b, b}, {b, b, a, a}, {b, b, a, b}, {b, b, b, a}, {b, b, b, b}}

DavidC
  • 16,724
  • 1
  • 42
  • 94
  • Apply seems a good option to. But using {{a,b},{c,d}}/.List->Sequence should be applied only once as a replace once rule, but it goes down the list generating Sequence[a, b, c, d] – Pankaj Sejwal Mar 17 '14 at 17:56
  • Hmmm. I wasn't aware of that. I'll try to fix it. – DavidC Mar 17 '14 at 19:50