Consider the following:
list={1/First[{}], 1, 2, 1/First[{}], 3};
DeleteCases[list,_NumberQ]
I wanted to remove all cases, which did not match _!NumberQ (e.g. 1/First[{}]), in the first place. But after DeleteCases[list,_!NumberQ] did not work, I tried it with DeleteCases[list,_NumberQ], just to see whether that would work...didn't.
What I am doing wrong?
Answer
The syntax _foo indicates that you're looking for a pattern with the head foo. NumberQ is not a Head, but a test returning a boolean True or False depending on whether the expression is a number or not. So you'd have to use it with PatternTest as _?NumberQ. For your example, the following should work:
Cases[list, _?NumberQ]
If you wanted to stick with DeleteCases, then you'll have to negate the test using either of the three constructs below:
DeleteCases[list, _?(Composition[Not, NumberQ])]
DeleteCases[list, _?(! NumberQ[#] &)]
DeleteCases[list, Except[_?NumberQ]]
Beware that ? has a very high precedence and binds very tightly and hence the parentheses are necessary in the first two constructs. See this question for more info.
Comments
Post a Comment