8

I would like to map a function that takes as an argument a list in a list of lists and an element of the list of lists. So for example, this is my list of lists:

{{4,1}, {3,1,1}, {2,2,1}}

I would like to map the function to the list of lists to obtain the following outcome:

{ {f[{4,1},4], f[{4,1},1]}, {f[{3,1,1},3}], f[{3,1,1},1], f[{3,1,1},1] }, {f[{2,2,1},2], f[{2,2,1},2], f[{2,2,1},1]}

I would appreciate it if someone could tell me how to do it. Thank you in advance!

Mavatanet
  • 141
  • 1

3 Answers3

7
ClearAll[g1,  f]
g1 = Function[x, f[x, #] & /@ x]

lst = {{4, 1}, {3, 1, 1}, {2, 2, 1}};

g1 /@ lst

{{f[{4, 1}, 4], f[{4, 1}, 1]},
{f[{3, 1, 1}, 3], f[{3, 1, 1}, 1], f[{3, 1, 1}, 1]},
{f[{2, 2, 1}, 2], f[{2, 2, 1}, 2], f[{2, 2, 1}, 1]}}

Also

ClearAll[g2, g3, g4]

g2[x_]:= Map[f[x, #] &] @ x
g2 /@ lst


g3 = Thread[f[#, #], List, {2}] & 
g3 /@ lst

g4[x_, y_] := f[x, #] & /@ y
g4[#, #] & /@ lst
kglr
  • 394,356
  • 18
  • 477
  • 896
7
lst = {{4, 1}, {3, 1, 1}, {2, 2, 1}};
Table[Table[f[i, j], {j, i}], {i, lst}]

{{f[{4, 1}, 4], f[{4, 1}, 1]}, {f[{3, 1, 1}, 3], f[{3, 1, 1}, 1], f[{3, 1, 1}, 1]}, {f[{2, 2, 1}, 2], f[{2, 2, 1}, 2], f[{2, 2, 1}, 1]}}

MelaGo
  • 8,586
  • 1
  • 11
  • 24
7

I like the techniques in the other answers (particularly the Table approach in the answer by MelaGo), but here are a few other options to add to the mix...

Given:

$list = {{4,1}, {3,1,1}, {2,2,1}};

Then any of the following expressions yield the desired result:

Curry[f, 2][#] /@ # & /@ $list

or

Cases[$list, l_ :> (f[l, #] & /@ l)]

or

Replace[$list, l_ :> (f[l, #] & /@ l), {1}]

or

MapIndexed[f[$list[[#2[[1]]]], #] &, $list, {2}]

or

ReplacePart[$list, {i_, j_} :> f[$list[[i]], $list[[i, j]]]]
WReach
  • 68,832
  • 4
  • 164
  • 269