# How to pass an expression as list elements for a Mathematica command

I'm trying to build a generic function that will calculate sums on different iterators. To simplify let consider:

Sum[x1 + x2 + x3, {x2, 2}, {x3, 2}];

MySum := Function[ Sum[x1 + x2 + x3, ##]];
(* I can call this function like this *)
MySum[{x2, 2}, {x3, 2}];

(*Now let's try an expression*)
xpr = {{x2, 2}, {x3, 2}};
(*Below still works*)
MySum [xpr[[1]], xpr[[2]] ]

(*How to make it generic for an arbitary number of elements?*)
imax = 2;
MySum [For[ i = 1, i <= imax, i++, xpr[[i]] ] ]


I would like to be able to call the function for 1 or 2 elements of the list generically.

• Your function is only adding up lists starting at 1, so on way to do this is by simply using Plus, Apply, Total, and Range like this MySum := Function[Plus @@@ (Range /@ ##) // Total]. Forget x1, x2, x3, etc and just send a list to MySum Commented Feb 26, 2019 at 4:12

This should work for any length of the xpr list:

MySum @@ xpr


Call just with the first element of xpr:

MySum @@ xpr[[{1}]]


Call just with the first, third, and fifth element of xpr:

MySum @@ xpr[[{1,3,5}]]