1
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ I don't really understand the question. Did you read the documentation? ? must be followed by a function and OddQ[x] is not a function. This question feels a bit like "I can compute a sum with Sum, but why can't I compute a sum with Product?" $\endgroup$ – Szabolcs Sep 2 at 8:00
  • 1
    $\begingroup$ PatternTest >> Properties and relations: "PatternTest applies test functions to patterns, which need not have names" and "Condition evaluates a Boolean expression on named parts of a pattern" $\endgroup$ – kglr Sep 2 at 8:10
  • 1
    $\begingroup$ possible duplicate: Using a PatternTest versus a Condition for pattern matching $\endgroup$ – kglr Sep 2 at 8:20
  • $\begingroup$ @kglr: Thank you. It is a duplicate by accident. $\endgroup$ – Money Sets You Free Sep 2 at 8:29
2
$\begingroup$

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

| improve this answer | |
$\endgroup$
  • 3
    $\begingroup$ 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. $\endgroup$ – Szabolcs Sep 2 at 8:52
0
$\begingroup$

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.

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ (OddQ[#] &) is OddQ , nearly no difference. $\endgroup$ – wuyudi Sep 2 at 8:11
  • 3
    $\begingroup$ Cases[Range[10], _?OddQ] $\endgroup$ – cvgmt Sep 2 at 9:06

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