2
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ try g[x1, x2] /. {x1 -> 1, x2 -> -2} // Trace to see what is happening. $\endgroup$ – kglr May 19 '16 at 0:10
  • $\begingroup$ 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! $\endgroup$ – Michael E2 May 19 '16 at 0:12
  • 1
    $\begingroup$ and Unevaluated[g[x1, x2]] /. {x1 -> 1, x2 -> -2} to get 1. $\endgroup$ – kglr May 19 '16 at 0:13
  • $\begingroup$ g @@ ({x1, x2} /. {x1 -> 1, x2 -> -2}) $\endgroup$ – Algohi May 19 '16 at 3:12
  • 1
    $\begingroup$ This question comes up fairly often; can anyone propose a canonical original which this should be marked as a duplicate of? $\endgroup$ – Mr.Wizard May 19 '16 at 6:41
5
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ I think NumericQ instead of NumberQ would be better. Try g2[x1, x2] /. {x1 -> 1, x2 -> -Pi}. (+1) $\endgroup$ – kglr May 21 '16 at 12:58
  • $\begingroup$ I agree. Will edit. $\endgroup$ – sorenba May 22 '16 at 2:00

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.