1

I can do the following

Cases[Range@10, x_ /; OddQ[x]]

But why cannot I do x_?OddQ[x] instead of _?OddQ in the following?

Cases[Range@10, x_ ? OddQ[x]]

Generally speaking, I am confused with using ? and /;.

Edit

After reading the existing comments and answer, I understood now that ? needs function. However, it still confused me, when we prefer ? to /; and vice versa?

Display Name
  • 2,009
  • 8
  • 17

2 Answers2

2

If you should use OddQ[x]

Cases[Range@10, x_?(x \[Function] OddQ[x])]

Edit

Thanks to the comment for pointing it out, the x in (x \[Function] OddQ[x]) is irrelevant to the first x, you can replace it with any other vars.

In other words, (x \[Function] f[x]) == Function[x,f[x]] == f[#]& == f

AsukaMinato
  • 9,758
  • 1
  • 14
  • 40
  • 3
    This is basically identical to what @Montevideo showed (use a pure function), but I find this version to be potentially misleading: you use x for two entire separate an unrelated purposes. Someone who is already confused about the difference between /; and ? could very well end up being even more confused, and believing that there is some connection between those two xs. – Szabolcs Sep 02 '20 at 08:52
0

You need to do this to solve this problem:

Cases[Range@10, x_?(OddQ[#] &)]

Cases[Range@10, x_?(OddQ)]

You may have confused pattern matching and conditional judgment functions.