5
$\begingroup$

Suppose I have a list of the form:

list = {a, b, {c, d}, f, {g, h}}

i.e. an element of the list could be another list. I want to 'thread' each element of the sublist, so for the above result I should obtain 4 lists:

{{a,b,c,f,g},{a,b,d,f,g},{a,b,c,f,h},{a,b,d,f,h}}

The list could have arbitrary size and the sublist are arbitrarily distributed. How can I do it?

NOTE: Originally I am trying to map expressions involving AND and OR into lists of the AND elements, e.g.

a && b && ( c || d ) && f && (g || h)

should be mapped to

{{a,b,c,f,g},{a,b,d,f,g},{a,b,c,f,h},{a,b,d,f,h}}

I concluded that substituting AND and OR by list was a good start, hence the above statement of the problem.

$\endgroup$
8
$\begingroup$
Distribute[list, List]

giving

{{a, b, c, f, g}, {a, b, c, f, h}, {a, b, d, f, g}, {a, b, d, f, h}}

$\endgroup$
  • 1
    $\begingroup$ +1 Also, Distribute[a && b && (c || d) && f && (g || h), Or, And, List, List] works directly upon the original boolean expression. $\endgroup$ – WReach May 24 '16 at 20:59
2
$\begingroup$

Not as elegant as Distribute, but there is also Tuples:

Tuples[List /@ list /. {{x__}} :> {x}]

{{a, b, c, f, g}, {a, b, c, f, h}, {a, b, d, f, g}, {a, b, d, f, h}}

and Outer:

Flatten[Outer[List, ## & @@ (List /@ list /. {{x__}} :> {x})], 4]

{{a, b, c, f, g}, {a, b, c, f, h}, {a, b, d, f, g}, {a, b, d, f, h}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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