Two-slot pure function

2

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

BBirdsell

Posted 2017-11-30T05:25:09.823

Reputation: 742

Question was closed 2017-12-01T22:12:58.487

(100*#[[1]])/(#[[2]]) & /@ p where p=Partition[data,2,1] is one way – Nasser – 2017-11-30T05:33:37.153

Okay that does work. :) Is there a way to use #1/#2 directly from data? Else the main big mystery remains. – BBirdsell – 2017-11-30T05:38:55.457

8I think (100*#2)/#1 & @@@ p is the cleanest way. – jjc385 – 2017-11-30T05:39:14.347

1Compare 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. – aardvark2012 – 2017-11-30T06:56:52.990

Mr.Wizard's answer here might be useful, too. – aardvark2012 – 2017-11-30T10:05:50.660

You need "apply at the first level", which is shorthanded @@@. – Αλέξανδρος Ζεγγ – 2017-11-30T12:12:51.973

Answers

5

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.

jjc385

Posted 2017-11-30T05:25:09.823

Reputation: 3 333