I am trying to define a substitution that gives 1 for odd numbers and 0 for even numbers. My guess was (in a particular example)

{0, 1, 2, 3, 4, 5, 6} /. N_Integer -> If[EvenQ[N], 0, 1]

But the output is {1,1,1,1,1,1,1}. The problem is in EvenQ[] which is acting on a symbol, but I specified before that it should be applied only to integers, so I do not understand why it does not work.

Where is the problem? Does it have something to do with ->?

closed as off-topic by Bob Hanlon, Henrik Schumacher, José Antonio Díaz Navas, J. M. is computer-less Oct 21 at 10:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Bob Hanlon, Henrik Schumacher, José Antonio Díaz Navas, J. M. is computer-less
If this question can be reworded to fit the rules in the help center, please edit the question.

In case speed matters Mod suggested by J.M. in comments is orders of magnitude faster than ReplaceAll and Boole:

SeedRandom[1]
input = RandomInteger[10^6, 10^6];
First[RepeatedTiming[res0 = input /. n_Integer :> If[EvenQ[n], 0, 1];]]

0.999

First[RepeatedTiming[ res1 = Boole@OddQ@input; ]]

.0226

First[RepeatedTiming[res2 =  With[{True = 1, False = 0}, Evaluate@OddQ[input]]; ]]

0.048

First[RepeatedTiming[ res3 = Mod[input, 2];]] 

0.00722

res0 == res1 == res2 == res3
> True

where the trick in res2 is from this answer by Mr.Wizard.

  • Nice trick! (But it's disappointing.) – Alan Oct 19 at 14:03

See JM's comment. The following points in a somewhat more general direction for some queries.

Boole@OddQ@Range[0, 6]
  • 3
    It should be Boole@OddQ@Range[0, 6] – rmw Oct 18 at 21:01

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