6
$\begingroup$

Say I have sets = {{a,b},{c,d},{e,f}} and I want to compute a sum like f[a,b] + f[c,d] + f[e,f]. One way to do this is to do

Sum[f[sets[[nSet]][[1]], sets[[nSet]][[2]]], {nSet, 1, Length[sets]}]

but this makes the notation cumbersome. It would be ideal to do something like

Sum[f[set[[1]], set[[2]]], set ∈ sets]

However, the function Sum[] doesn't allow indexation over abstract set other than a list of numbers. How can I implement this?

I'm asking because I need to do a lengthy computation involving sums and products over partitions, sets and mappings. And with the first option I wrote it really gets unhandleable.

$\endgroup$

4 Answers 4

11
$\begingroup$

The summation index can run over a set, but instead of set ∈ sets the syntax is

Sum[f[set[[1]],set[[2]]],{set,sets}]
(* f[a,b]+f[c,d]+f[e,f] *)

I would probably use

Total[f@@@sets]
(* f[a,b]+f[c,d]+f[e,f] *)

This uses:

  • @@@ which is a shorthand for MapApply. Evaluate f@@@sets to see what it does.
  • The Total function which adds all elements of a list.
$\endgroup$
1
  • 1
    $\begingroup$ Beautiful, it was so simple. I still have a lot of syntax to learn from Mathematica. Thanks! $\endgroup$ Oct 26, 2022 at 13:58
9
$\begingroup$

Also,

Inner[f, Sequence @@ Transpose@{{a, b}, {c, d}, {e, g}}, Plus]
$\endgroup$
7
$\begingroup$

Just another way:

Total@MapThread[f[#1, #2] &, Transpose@sets]
(*f[a, b] + f[c, d] + f[e, f]*)
$\endgroup$
6
$\begingroup$

One possible way out of many is

lis = {{a, b}, {c, d}, {e, f}}
Plus @@ Map[f[Sequence @@ #] &, lis]

Mathematica graphics

Had to use Sequence @@ # in there, because just doing

Map[f, lis]

Gives

Mathematica graphics

Instead of the following when using Sequence @@ #

Mathematica graphics

@@ can be replaced by Apply if you prefer that.

$\endgroup$
1
  • $\begingroup$ Same comment I made above. Sorry I can't yet upvote and I can only accept one answer. It was helpful to see more options though. Thanks! $\endgroup$ Oct 26, 2022 at 13:59

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.