Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
Compile[{{x, _Real, 1}}, MemberQ[x, 2]][{2}]

outputs False.

In fact, it seems to get compiled as False for every input if you look at a CompilePrint. It doesn't call the main evaluator, and MemberQ is included in the Compile`CompilerFunctions[] list

Any ideas?

share|improve this question
Compile[{{x, _Integer, 1}}, MemberQ[x, 2]] works; Compile[{{x, _Real, 1}}, MemberQ[x, 2.]] also works. MemberQ[{2.}, 2] might help you figure out why. – J. M. May 23 '12 at 5:15
@JM, I'm not sure of the protocol, but I'll post an answer and if that's not what I'm supposed to do, I'll delete it. I'll sure delete it if you post yours – Rojo May 23 '12 at 5:42
No worries, I upvoted your answer. I didn't feel like elaborating today, and wanted you to piece things together yourself, so I just left a comment. – J. M. May 23 '12 at 6:11

Some more insight can be obtained using CompilePrint:

 Compile[{{x, _Real, 1}},
  MemberQ[x, 2]]

Mathematica graphics

(ie, it works out that it's always false due to the type), versus

 Compile[{{x, _Integer, 1}},
  MemberQ[x, 2]]

Mathematica graphics

which does the usual thing.

share|improve this answer
huh, didn't know about CompilePrint, nice! – tkott May 23 '12 at 10:38
up vote 8 down vote accepted

OK, as J. M. pointed out, it was an issue of types. x was defined to be of Real type, so it was converted and treated as such in the compiled code. Since a 2 can never be a member of a vector of Reals, the compiler hard-coded the result False, which is correct.

share|improve this answer
In general: if you're going to be dealing with reals entirely within your compiled code, make all hard-coded constants reals, and similarly with integers. With[] might be useful here for injecting things like N[Sqrt[2]] or N[Pi] into your code to be compiled. – J. M. May 23 '12 at 6:13

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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