5
$\begingroup$

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.

$\endgroup$
  • 4
    $\begingroup$ Just a wild guess: {a, b, c} /. List -> Sequence does something like this work? $\endgroup$ – bobthechemist Mar 17 '14 at 17:29
  • $\begingroup$ I generally don't face it, in fact I have answered 2-3 questions that used it, but I don't know what the problem is. It is converting all sublists to sequences. $\endgroup$ – Rorschach Mar 17 '14 at 17:33
  • $\begingroup$ @bobthechemist it certainly does! $\endgroup$ – Aron May 29 '14 at 17:41
5
$\begingroup$

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 *)
$\endgroup$
  • $\begingroup$ I tried using slotsequence,looks like I wasn't getting the syntax right. Thanks :) $\endgroup$ – Rorschach Mar 17 '14 at 17:41
  • $\begingroup$ Good example of SlotSequence, which I never seem to think of. $\endgroup$ – DavidC Mar 17 '14 at 17:48
  • $\begingroup$ I believe that Flatten argument 2 should be n-1 .. $\endgroup$ – george2079 Jun 9 '17 at 15:53
3
$\begingroup$

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}}

$\endgroup$
  • $\begingroup$ 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] $\endgroup$ – Rorschach Mar 17 '14 at 17:56
  • $\begingroup$ Hmmm. I wasn't aware of that. I'll try to fix it. $\endgroup$ – DavidC Mar 17 '14 at 19:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.