Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
1  
Just a wild guess: {a, b, c} /. List -> Sequence does something like this work? –  bobthechemist Mar 17 at 17:29
    
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. –  Rorschach Mar 17 at 17:33
    
@bobthechemist it certainly does! –  Aron May 29 at 17:41

2 Answers 2

up vote 5 down vote accepted

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 *)
share|improve this answer
    
I tried using slotsequence,looks like I wasn't getting the syntax right. Thanks :) –  Rorschach Mar 17 at 17:41
    
Good example of SlotSequence, which I never seem to think of. –  David Carraher Mar 17 at 17:48

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

share|improve this answer
    
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] –  Rorschach Mar 17 at 17:56
    
Hmmm. I wasn't aware of that. I'll try to fix it. –  David Carraher Mar 17 at 19:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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