1
$\begingroup$

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

and

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.

Thanks!

$\endgroup$
2
$\begingroup$

Probably something like this would work:

f := (If[AllTrue[{##}, IntegerQ] , +##]) &
$\endgroup$
  • 1
    $\begingroup$ Brilliant! 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! $\endgroup$ – A is for Ambition Jun 25 '15 at 8:33
  • $\begingroup$ @AisforAmbition, Glad to help:) $\endgroup$ – Algohi Jun 25 '15 at 8:34
  • 1
    $\begingroup$ More classically: MatchQ[{##}, {__Integer}]. $\endgroup$ – J. M. will be back soon Jun 25 '15 at 8:55

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.