# MemberQ weird inside Compile

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 CompileCompilerFunctions[] list

Any ideas?

-
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. –  Guess who it is. 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. –  Guess who it is. May 23 '12 at 6:11

Some more insight can be obtained using CompilePrint:

Needs["CompiledFunctionTools"];
CompilePrint[
Compile[{{x, _Real, 1}},
MemberQ[x, 2]]
]


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

Needs["CompiledFunctionTools"];
CompilePrint[
Compile[{{x, _Integer, 1}},
MemberQ[x, 2]]
]


which does the usual thing.

-
huh, didn't know about CompilePrint, nice! –  tkott May 23 '12 at 10:38

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.

-
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. –  Guess who it is. May 23 '12 at 6:13