4
$\begingroup$

I'm trying to define a pattern that will match lists of lists, where the inner lists contains only numbers (I want the sum of each list). Like this

{{1, 2}, {3, 4}}

But not like this

{1, {1, 3},{{3}}}

Why this is not working?

Clear[foo];
foo[x : {v___List}] := Plus @@@ x /; VectorQ[v, NumberQ]

Thank you!

$\endgroup$
1
  • $\begingroup$ your condition VectorQ[v, NumberQ] for v=Sequence[{1, 2}, {3, 4}] becomes VectorQ[{1, 2}, {3, 4}, NumberQ] thus you get the error message VectorQ::argt: VectorQ called with **3** arguments; 1 or 2 arguments are expected. $\endgroup$
    – kglr
    Commented Aug 21, 2018 at 20:00

2 Answers 2

7
$\begingroup$
ClearAll[foo];
foo[x : {___List?(VectorQ[#, NumberQ] &)}] := Plus @@@ x

foo[{{1, 2}, {2, 3, 4}}]

{3, 9}

foo[{{1, 2}, {{3}}}]

foo[{{1, 2}, {{3}}}]

Note: You need to use NumericQ in place of NumberQ if you want foo[{{1, 2}, {2, 3, π}}] to return {3, 2 + 3 π}.

$\endgroup$
4
$\begingroup$

Another approach is to use Total, with a condition to forbid it from totaling entries with a single term:

f[x_] := If[Length[x] > 1, Total[x], x]

For instance:

f /@ {{1, 2}, {2, 3, 4}}
{3, 9}
f /@ {{1, 2}, {2, 3, 4}, {{3}}}
{3, 9, {{3}}}
$\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.