4
$\begingroup$

I want to apply a function to members of a list only if all the members of the list satisfy a set of conditions otherwise return a result of zero. For example for

list1 = {0, "", " ", 1, 5, 6};
list2 = {1, 4, 3, 6, 7, 9, 9, 11};

the desired output would be

f[list1]
f[list2] (* e.g. Plus@@list *)

0

50

What I've tried so far:

f[list_] := 
 If[(# == 0 || N[#] == "" || N[#] == " "), 0, 
    Plus @@ list] & /@ list
f[list1]
f[list2]

{0, 0, 0, 12 + "" + " ", 12 + "" + " ", 12 + "" + " "} {50, 50, 50, 50, 50, 50, 50, 50}

It's clear to me why this didn't work but I can't quite see the appropriate chicanery. Any suggestions?

$\endgroup$
3
$\begingroup$
ClearAll[f]
f[list_] := If[FreeQ[list, 0 | "" | " "], Plus @@ list, 0]

f[list1]

0

f[list2]

50

Alternatively,

ClearAll[f2]
f2[list_] := Boole[FreeQ[list, 0 | "" | " "]] Plus @@ list;

f2[list1]

0

f2[list2]

50

Or

ClearAll[f3]
f3[lst : {Except[Alternatives[0, "", " "]] ..}] := Plus @@ lst
f3[{__}] := 0

f3[list1]

0

f3[list2]

50

| improve this answer | |
$\endgroup$
2
$\begingroup$

Another way to build the function is:

g[x_] := If[Length@Select[x, NumberQ] == Length[x], Total[x], 0];
{g[list1], g[list2]}
{0, 50}
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.