# replacement rule doesn't work

I define a function which counts the number of negative elements in a list as follows:

g[x1_, x2_] := Count[{x1, x2}, _?Negative]


Plugging in values shows that it does what it's supposed to do

g[1, -2]


returns 1

For some reason using replacement rules doesn't work as expected

g[x1, x2] /. {x1 -> 1, x2 -> -2}


returns 0

Thanks for the answers. I am not quite clear on why Count behaves differently from any other function. If I define

g[x1_,x2_]:= x1+x2


it works just fine. Why is in the case of Count anything evaluated before it gets values in the first place? Is this a bug? I thought that using set delayed (:=) in my function definition would prevent the RHS to be evaluated?

• try g[x1, x2] /. {x1 -> 1, x2 -> -2} // Trace to see what is happening. – kglr May 19 '16 at 0:10
• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 May 19 '16 at 0:12
• and Unevaluated[g[x1, x2]] /. {x1 -> 1, x2 -> -2} to get 1. – kglr May 19 '16 at 0:13
• g @@ ({x1, x2} /. {x1 -> 1, x2 -> -2}) – Algohi May 19 '16 at 3:12
• This question comes up fairly often; can anyone propose a canonical original which this should be marked as a duplicate of? – Mr.Wizard May 19 '16 at 6:41

The problem is that g[x1, x2] returns 0 with your definition and this is evaluated before the substitutions are applied. You could define
g2[x1_?NumericQ, x2_?NumericQ] := Count[{x1, x2}, _?Negative]

to hold off evaluation until values has been given to x1 and x2. Then g2[x1, x2] just returns g2[x1, x2] and g2[x1, x2] /. {x1 -> 1, x2 -> -2} return 1 as desired.
• I think NumericQ instead of NumberQ would be better. Try g2[x1, x2] /. {x1 -> 1, x2 -> -Pi}. (+1) – kglr May 21 '16 at 12:58