1
$\begingroup$

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]}
$\endgroup$
2
  • 7
    $\begingroup$ Times @@@ Apply[p, list, {2}]? $\endgroup$ Oct 9, 2015 at 5:44
  • $\begingroup$ This is great and simple, thanks! $\endgroup$ Oct 9, 2015 at 6:20

2 Answers 2

10
$\begingroup$

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.

$\endgroup$
1
  • 1
    $\begingroup$ 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. $\endgroup$ Oct 9, 2015 at 6:24
0
$\begingroup$
☺ @ ☺☺_ := 1 ## & @@ ☺☺ @@@ # & /@ # &;

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

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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