Sum of Integers with a Pure Function


How would I find the sum of an argument, with the constraint that they are all integers (so if the argument contains a non-integer value, the function will not evaluate).

I came up with these two:

sumInts[n__?(IntegerQ[#] &)] := +n


sum[x__Integer] := +x

Both are impure functions (though the first function uses a pure predicate). How would I go about making a pure function? I couldn't figure out how to because of the Integer constraint.


A is for Ambition

Posted 2015-06-25T07:48:19.607

Reputation: 465



Probably something like this would work:

f := (If[AllTrue[{##}, IntegerQ] , +##]) &


Posted 2015-06-25T07:48:19.607

Reputation: 19 067

1Brilliant! I'm very new to Mathematica, so I'm often unable to come up with more creative solutions since I'm unfamiliar with a lot of the functions such as If and AllTrue. Thank you very much! – A is for Ambition – 2015-06-25T08:33:29.867

@AisforAmbition, Glad to help:) – Algohi – 2015-06-25T08:34:39.003

1More classically: MatchQ[{##}, {__Integer}]. – J. M.'s ennui – 2015-06-25T08:55:22.950