1
$\begingroup$

I have the following list:

list = {{1, 2}, {2}, {3, 4, 1}, {5, 4}, {3, 3}, {a, b, c}, {e, f}, {g}, {}, {Sin[a], Cos[b]}};

I should use Cases function Cases[list, pattern -> expr] with patterns or rules to get the following sums:

(a) the sum of all subexpressions with the length 2. Result:

{3,9,6,e+f,Cos[b]+Sin[a]}

(b) as in (a), but only for Integer numbers. Result:

{3,9,6}

(c) the sum of all subexpressions with the length >= 2. Result:

{3,8,9,6,a+b+c,e+f,Cos[b]+Sin[a]}

(d) the sum of ALL subexpressions. Result:

{3,2,8,9,6,a+b+c,e+f,g,0,Cos[b]+Sin[a]}

PS. It's not a homework. I learn for a test. This is an exercise I don't understand. Thanks for your help!

$\endgroup$
3
  • 1
    $\begingroup$ Can you show us what you have tried so far? $\endgroup$
    – MarcoB
    Commented May 6, 2015 at 14:45
  • $\begingroup$ Cases[list, _?(Total[[Length[#] == 2], Infinity] &)] but it doesn't work $\endgroup$
    – user29279
    Commented May 6, 2015 at 14:54
  • $\begingroup$ You were almost there, you just mashed up replacements and tests together. Cases[list, _?(Length[#] == 2 &)] picks out the right elements, Total/@Cases[list, _?(Length[#] == 2 &)] gets their sums. $\endgroup$
    – LLlAMnYP
    Commented May 6, 2015 at 18:27

2 Answers 2

3
$\begingroup$
Cases[list, x : {_, _} :> Plus @@ x]
(* {3, 9, 6, e + f, Cos[b] + Sin[a]} *)

Cases[list, x : {_Integer, _Integer} :> Plus @@ x]
(* {3, 9, 6} *)

Cases[list, x : {_, __} :> Plus @@ x]
(* {3, 8, 9, 6, a + b + c, e + f, Cos[b] + Sin[a]}*)

Cases[list, x : {___} :> Plus @@ x]
(* {3, 2, 8, 9, 6, a + b + c, e + f, g, 0, Cos[b] + Sin[a]} *)

Or

patterns = {{_, _}, {_Integer, _Integer}, {_, __}, {___}};

Cases[list, x : # :> Plus @@ x] & /@ patterns
(* {{3, 9, 6, e + f, Cos[b] + Sin[a]}, 
    {3, 9, 6}, 
    {3, 8, 9, 6, a + b + c, e + f, Cos[b] + Sin[a]}, 
    {3, 2, 8, 9, 6, a + b + c, e + f, g, 0, Cos[b] + Sin[a]}} *)
$\endgroup$
0
$\begingroup$

Repeated can be very helpful. Also you can use +x as a shorthand for Plus[x], and x can be bound to a sequence. _Integer is the pattern for an expression with head Integer. (For my description of heads please see Is there a summary of answers Head[] can give? and Why can't a string be formed by head String?) Therefore for (b):

Cases[list, {x : Repeated[_Integer, {2}]} :> +x]
{3, 9, 6}

To sum all sublists I would either use Total or Map Tr across the list:

Total[list, {2}]

Tr /@ list
{3, 2, 8, 9, 6, a + b + c, e + f, g, 0, Cos[b] + Sin[a]}   (* output from either *)
$\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.