5
$\begingroup$
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?

$\endgroup$
  • 2
    $\begingroup$ 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. $\endgroup$ – J. M. will be back soon May 23 '12 at 5:15
  • $\begingroup$ @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 $\endgroup$ – Rojo May 23 '12 at 5:42
  • $\begingroup$ 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. $\endgroup$ – J. M. will be back soon May 23 '12 at 6:11
8
$\begingroup$

Some more insight can be obtained using CompilePrint:

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

Mathematica graphics

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

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

Mathematica graphics

which does the usual thing.

$\endgroup$
  • $\begingroup$ huh, didn't know about CompilePrint, nice! $\endgroup$ – tkott May 23 '12 at 10:38
8
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ 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. $\endgroup$ – J. M. will be back soon May 23 '12 at 6:13

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.