3
$\begingroup$

I am trying to do simple operations with several lists. In this context, I was wondering if a sum over Slot is possible inside MapThread.

Here is a simple example:

l1={{f1,ff1},{g1,gg1}};
l2={{f2,ff2},{g2,gg2}};
l0={l1,l2};

MapThread[{Slot[1][[1]], Slot[1][[2]]+Slot[2][[2]]} &, l0]
(**MapThread[{#1[[1]], #1[[2]]+#2[[2]]} &, l0]**)

which produces the expected result:

{{f1, ff1 + ff2}, {g1, gg1 + gg2}}

However, I wanted to do something like

MapThread[{Slot[1][[1]], Sum[Slot[$i][[2]],{$i,1,Length[l0]}]} &, l0]

which however does not work. I am trying to do this because then I don't have to worry about how many l1,l2,... are there inside l0.

$\endgroup$
6
  • 1
    $\begingroup$ As an alternative you could use MapAt[First, {All, 1}]@MapThread[Plus, l0, 2] $\endgroup$
    – eldo
    Apr 24 at 10:44
  • $\begingroup$ @eldo Thanks! This works as expected. Btw, if I may ask, what is 2 for inside MapThread[Plus, l0, 2]? $\endgroup$
    – BabaYaga
    Apr 24 at 10:53
  • 2
    $\begingroup$ Try: MapThread[{Slot[1][[1]], Total[{##}[[All, 2]]]} &, l0] $\endgroup$ Apr 24 at 11:51
  • 1
    $\begingroup$ The 2 means Level 2 (see documentation for MapThread). The inaccuracy doesn't arise with Daniels`s comment / answer. $\endgroup$
    – eldo
    Apr 24 at 12:03
  • 1
    $\begingroup$ In addition, l1 + MapAt[0 &, l2, {All, 1}] $\endgroup$
    – user1066
    Apr 24 at 16:23

1 Answer 1

4
$\begingroup$

DanielHubers's solution in the comments is nice, but another option is to deal with the structural transformation directly rather than implicitly inside of the function you're threading. So, maybe something like this:

Map[Comap[{Extract[{1, 1}], Total@*Last}], Transpose[l0, {3, 1, 2}]]

Comap is new, and the point-free style can be confusing, so an alternate might be:

Map[{#[[1, 1]], Total[#[[2]]]} &, Transpose[l0, {3, 1, 2}]]
$\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.