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$
4
  • 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
    Commented Sep 2, 2020 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
    Commented Sep 2, 2020 at 8:10
  • 1
    $\begingroup$ possible duplicate: Using a PatternTest versus a Condition for pattern matching $\endgroup$
    – kglr
    Commented Sep 2, 2020 at 8:20
  • $\begingroup$ @kglr: Thank you. It is a duplicate by accident. $\endgroup$ Commented Sep 2, 2020 at 8:29

2 Answers 2

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

$\endgroup$
1
  • 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
    Commented Sep 2, 2020 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.

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

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