2
$\begingroup$

I come across this problem in many different forms when doing arithmetic in MMA and have until now just suffered along doing it the long way – having given up trying to figure it out myself – but now I have to admit that's getting a bit repetitive.

How does one get two slots working in a pure function? I'm trying to work out the % differences in the following list but it just returns can not be filled errors.

data={16,24,36,54,81};
(100*#2)/#1 &/@ Partition[data,2,1]

sample image

$\endgroup$

closed as off-topic by Bob Hanlon, LCarvalho, m_goldberg, b3m2a1, Sektor Dec 1 '17 at 22:12

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Bob Hanlon, LCarvalho, m_goldberg, b3m2a1, Sektor
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ (100*#[[1]])/(#[[2]]) & /@ p where p=Partition[data,2,1] is one way $\endgroup$ – Nasser Nov 30 '17 at 5:33
  • $\begingroup$ Okay that does work. :) Is there a way to use #1/#2 directly from data? Else the main big mystery remains. $\endgroup$ – BBirdsell Nov 30 '17 at 5:38
  • 8
    $\begingroup$ I think (100*#2)/#1 & @@@ p is the cleanest way. $\endgroup$ – jjc385 Nov 30 '17 at 5:39
  • 1
    $\begingroup$ Compare the output of f[#1, #2] & @@@ Partition[data, 2, 1] with that of f[#] & /@ Partition[data, 2, 1] (for undefined f). @@@ replaces the head, List, of each sublist with f, whereas /@ applies f to each sublist. $\endgroup$ – aardvark2012 Nov 30 '17 at 6:56
  • $\begingroup$ Mr.Wizard's answer here might be useful, too. $\endgroup$ – aardvark2012 Nov 30 '17 at 10:05
5
$\begingroup$

With p=Partition[data,2,1], you can do any of the following :

(100*#2)/#1 & @@@ p   (* parsed as Apply[ (100*#2)/#1 &, p, {1} ] *)
Apply[ (100*#2)/#1 & ] /@ p
(100*#[[2]])/(#[[1]]) & /@ p  (* Credit to Nasser in the comments *)

All evaluate to {150, 150, 150, 150}.


Your original try failed because Map (/@) passes only one argument to the function -- for example, #1 gets replaced by {16,24} for the first element of p. You need to take parts of #1 (which is equivalent to #), as in Nasser's example (the third example I included above), or you need to use Apply to pass 16 and 24 as the first and second arguments, as you seem to desire.

$\endgroup$

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