2
$\begingroup$

This seems like a very simple question, the answer to which should be obvious to me. So I won't be offended if this question is closed. But I'm having trouble figuring out the answer.

I would like to write a function that returns True if a list contains one or more numbers greater than 1. Why does MemberQ[{2, 1}, # > 1 &] return False? Thanks.

$\endgroup$
  • 2
    $\begingroup$ Select[{2, 1}, # > 1 &] != {} $\endgroup$ – Dr. belisarius Oct 17 '12 at 16:13
  • 1
    $\begingroup$ Catch[Scan[If[# > 1, Throw[True]] &, {1, 2, 6, 8}]] $\endgroup$ – Dr. belisarius Oct 17 '12 at 16:19
  • 2
    $\begingroup$ Simply put, the second argument of MemberQ[] should be a pattern, not a test. What does MatchQ[2, # > 1 &] return? $\endgroup$ – J. M. is away Oct 17 '12 at 16:28
  • 3
    $\begingroup$ The comment by @J.M. answers your question; if you insist on using MemberQ you can do MemberQ[{2, 1}, _?(# > 1 &)] to transform a test into a pattern. $\endgroup$ – b.gates.you.know.what Oct 17 '12 at 16:37
  • 2
    $\begingroup$ The simplest way is clearly ! IntegerQ@Log2[1 + FromDigits[UnitStep[1 - {1, 2}]~Prepend~1, 2]] $\endgroup$ – Rojo Oct 17 '12 at 18:44
7
$\begingroup$

As J. M. kindly points out, I must specify form as a pattern, not a test. Thus, as b.gatessucks kindly points out, I must instead use:

MemberQ[{2, 1}, _?(# > 1 &)]

or one of the other suggestions given as comments to the original post.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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