What I thought the second part would do is to check each argument to p that occurs in this sum and replace p[x] with 1 if x is either 0 or 5 and with 0 if x is anything else. I thought, in short, the result would be 2. That's not, however, what I get. Instead Mathematica returns 0. What am I doing wrong?

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

8

Just change -> with :> ;) (you want the function on the right to evaluate on substitution and not when defining the rule, this is called a delayed rule, you can find more on the help.)
–
Spawn1701DApr 16 '13 at 2:07

D'oh! That did the trick. Thank you very much!
–
RoyalTSApr 16 '13 at 2:13

From this, as you've been told, the use of RuleDelayed[] (:>) instead of Rule[] (->) is paramount here. Let me present a different way to do your replacement rule:

s /. p[x_] :> Boole[MatchQ[x, 0 | 5]]
2

To explain: Alternatives (|) is a pattern that allows you to match any of its arguments; thus, 0 | 5 means "match either of 0 or 5". You can then use MatchQ[] to test if x matches that pattern, and Boole[] then converts True and False into 0 and 1 respectively (i.e. an Iverson bracket).

Mathematica is a registered trademark of Wolfram Research, Inc. While the mark is used herein with the limited permission of Wolfram Research, Stack Exchange and this site disclaim all affiliation therewith.