2
$\begingroup$

I tried to understand the mechanism of pure function tricks. Imaging I have a nested list generated by:

list=Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}]

Result:

>    {{{1, -1}, {1, 1}}, {{3, -3}, {3, -1}, {3, 1}, {3,     3}}, {{5,
> -5}, {5, -3}, {5, -1}, {5, 1}, {5, 3}, {5,     5}}, {{7, -7}, {7, -5}, {7, -3}, {7, -1}, {7, 1}, {7, 3}, {7,     5}, {7, 7}}, {{9, -9}, {9,
> -7}, {9, -5}, {9, -3}, {9, -1}, {9,     1}, {9, 3}, {9, 5}, {9, 7}, {9, 9}}}

And a function:

Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]

I want the Fun to apply to each pair of the list to calculate the sum of all the result.

Should I use something like Fun[#1,#2]&/@list ? But it never works out, idk why.Thanks for your help!

$\endgroup$
1
  • $\begingroup$ Take a look at Mike's and Chris's answers, and notice the difference between Apply and Map, both are great tools, both can be made to work in the same situations, but usually one is more suited to the task at hand. Compare the results of f @@ {1, 2}, f @@@ {{1, 2}, {3, 4}, {5, 6}}, and f /@ {{1, 2}, {3, 4}, {5, 6}} $\endgroup$
    – Jason B.
    Jan 25, 2018 at 22:05

4 Answers 4

3
$\begingroup$

Apply Fun at level 2 of list.

list = Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}];

Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]

Apply[Fun, list, {2}]
$\endgroup$
2
$\begingroup$

Why not just re-define your function to

Fun2[{x_, y_}] := Total[Sqrt[x^2 + y^2]]

then

Map[Fun2, list, {2}]
$\endgroup$
1
$\begingroup$

You can solve your problem as follows:

llist = Flatten[list, 1]
Apply[Fun, llist, 1]

If the structure of list should be kept

Table[Apply[Fun, list[[i]], -1], {i, 1, Length[list]}]
$\endgroup$
0
$\begingroup$

If you wish to keep the structure of the list you can do something like

In[1]:= list = Table[{p, q}, {p, 1, 9, 2}, {q, -p, p, 2}];

In[2]:= Fun[x_, y_] := Total[Sqrt[x^2 + y^2]]

In[3]:= Map[Fun @@ # &, list, {2}]

Out[3]= {{5/2, 5/2}, {3 + Sqrt[2], 21/2, 21/2, 
  3 + Sqrt[2]}, {5 + Sqrt[2], 69/2, 53/2, 53/2, 69/2, 
  5 + Sqrt[2]}, {7 + Sqrt[2], 149/2, 117/2, 5 + Sqrt[2], 5 + Sqrt[2], 
  117/2, 149/2, 7 + Sqrt[2]}, {9 + Sqrt[2], 261/2, 213/2, 
  3 + Sqrt[10], 165/2, 165/2, 3 + Sqrt[10], 213/2, 261/2, 
  9 + Sqrt[2]}}
$\endgroup$

Your Answer

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

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