# How to do this replacement without a for loop?

I'm new to Mathematica and I'm trying to get past my desire to use For loops for everything; can somebody tell me a simple way to make this replacement? I want my input to be

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


and my output to be

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

• Times @@@ Apply[p, list, {2}]? Commented Oct 9, 2015 at 5:44
• This is great and simple, thanks! Commented Oct 9, 2015 at 6:20

J.M.'s answer in comments is what I would have done too.

Times @@@ Apply[p, list, {2}]


But for completeness, you might be interested in this rule-based method of getting the p elements:

Times @@@ (a /. {x_?AtomQ, y_?AtomQ} -> p[x, y])


The test for _AtomQ is important (you could also use _?NumericQ or simple pattern _Integer, depending on the scope of your actual problem). Otherwise the rule will just match the top level of your nested list and not replace anything else.

This being Mathematica, there are many ways to get the same result, but J.M.'s is the most succinct that I can think of.

• In effect, the snippet I gave applies twice; first, at level 2 to replace the head List with p ({{p[1,2], p[3,4]}, {p[1,4], p[2,3]}}), and then at level one to replace List with Times. Commented Oct 9, 2015 at 6:24
☺ @ ☺☺_ := 1 ## & @@ ☺☺ @@@ # & /@ # &;

☺[p] @ {{{1, 2}, {3, 4}}, {{1, 4}, {2, 3}}}


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

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


Using MapApply (new in 13.1)

MapApply[Times, MapApply[p] /@ list]
`

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