5
$\begingroup$

I have the following line of code:

Plus @@ Table[p[x], {x, 0, 20}] /. p[x_] -> Boole[MemberQ[{0, 5}, x]]

The first part of this produces

p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7] + p[8] + p[9] + p[10] +
p[11] + p[12] + p[13] + p[14] + p[15] + p[16] + p[17] + p[18] + p[19] + p[20]

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?

$\endgroup$
3
  • 8
    $\begingroup$ 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.) $\endgroup$
    – Spawn1701D
    Commented Apr 16, 2013 at 2:07
  • $\begingroup$ D'oh! That did the trick. Thank you very much! $\endgroup$
    – RoyalTS
    Commented Apr 16, 2013 at 2:13
  • $\begingroup$ mathematica.stackexchange.com/questions/22917/… could be of interest... $\endgroup$ Commented Apr 16, 2013 at 5:47

2 Answers 2

5
$\begingroup$

Try this:

    Clear[p];
p[x_] := Boole[MemberQ[{0, 5}, x]];
Plus @@ Table[p[x], {x, 0, 20}]

this:

Plus @@ Table[Boole[MemberQ[{0, 5}, x]], {x, 0, 20}]

this:

Plus @@ Table[p[x], {x, 0, 20}] /. 
     p[x_] -> UnitBox[x] + UnitBox[x - 5]

this:

Plus @@ Table[UnitBox[x] + UnitBox[x - 5], {x, 0, 20}]

or this:

Sum[UnitBox[x] + UnitBox[x - 5], {x, 0, 20}]
$\endgroup$
0
$\begingroup$

You can certainly use Sum[] to directly generate your sum of p[]'s:

s = Sum[p[x], {x, 0, 20}];

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).

$\endgroup$

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