0

Let's say I have two lists, and I'd like to generate a "cartesian product" from these two. Specifically

Inputs:

A = {{{1}}, {{2}}, {{1}, {2}}};
B = {8, 9};

Desired output:

X = {{{{1}} -> 8, {{1}} -> 9}, {{{2}} -> 8, {{2}} -> 9}, {{{1}, {2}} -> 
   8, {{1}, {2}} -> 9}}

I tried

f[#1, #2]& /@ {A, B}

but it didn't work. I also tried to use Thread, but that didn't work either.

Edit

Outer doesn't really work either, since it goes to all the leaves and extracts them first.

Outer[#1 -> #2, A, B]

{{{{1 -> 8, 1 -> 9}}}, {{{2 -> 8, 2 -> 9}}}, {{{1 -> 8, 1 -> 9}}, {{2 -> 8, 2 -> 9}}}}

cartonn
  • 1,005
  • 6
  • 15

3 Answers3

3

You just need to apply the third argument of Outer as rm -rf suggested. With your A and B,

Outer[#1 -> #2 &, A, B, 1]

gives

{{{{1}} -> 8, {{1}} -> 9}, {{{2}} -> 8, {{2}} -> 9}, {{{1}, {2}} ->  8, {{1}, {2}} -> 9}}

as you requested. To check (with your X)

Outer[#1 -> #2 &, A, B, 1] == X

True
bill s
  • 68,936
  • 4
  • 101
  • 191
1

I may be misinterpreting, but is this what you are looking for ?

Outer[f, {a, b, c}, {1, 2, 3}]

(* {{f[a, 1], f[a, 2], f[a, 3]}, {f[b, 1], f[b, 2], 
  f[b, 3]}, {f[c, 1], f[c, 2], f[c, 3]}} *)
Clif
  • 697
  • 4
  • 12
1

How about this:

A = {{{1}}, {{2}}, {{1}, {2}}};
B = {8, 9};
Table[{i -> j}, {i, A}, {j, B}]

which gives me:

{{{{{1}} -> 8}, {{{1}} -> 9}}, {{{{2}} -> 8}, {{{2}} -> 
    9}}, {{{{1}, {2}} -> 8}, {{{1}, {2}} -> 9}}}

I've got one too many sets of braces, it looks like.

bobthechemist
  • 19,693
  • 4
  • 52
  • 138