11
$\begingroup$

Could somebody explain why

test = Compile[{{x}},
      Return[x];
    ];
test[0.]

returns

Compile::cret: "The type of return values in Return[x]; are different. Evaluation will use the uncompiled function. "

while

test = Compile[{{x}},
      Return[x]
    ];
test[0.]

works as expected? Notice that the only difference is the semicolon at the end of Return.

$\endgroup$

1 Answer 1

8
$\begingroup$

This question is closely related. See ruebenkoe's answer in particular.

I think you get this behaviour because:

  1. Compiled code is typed, so Compile can only return one type of result (and the type needs to be a number, not a symbol)

  2. When Compile analyses the code, it perceives it as something that returns Null. fun[x]; is equivalent to fun[x]; Null. So even though you have a single Return which will always break out of the function (returning a number), Compile is not able to realize this.

    Further proof that this is the case is that the following compiles fine:

    test = Compile[{{x}}, Return[x]; 0.0]
    
$\endgroup$
16
  • $\begingroup$ Aha (I suspected as much), but then I would argue this is a bug in Compile. Since the return value is x and not 0.0. So it does not matter what comes after return. $\endgroup$
    – Ajasja
    Jun 22, 2012 at 8:07
  • $\begingroup$ Also this is strange as well f = Function[x, Return[x];]; f[0.] $\endgroup$
    – Ajasja
    Jun 22, 2012 at 8:08
  • $\begingroup$ test = Compile[{{x}}, x]; on the other hand seems to work fine. $\endgroup$ Jun 22, 2012 at 8:20
  • $\begingroup$ @image_doctor Yes, because in that case there return type can clearly only be one thing---a number. $\endgroup$
    – Szabolcs
    Jun 22, 2012 at 8:24
  • $\begingroup$ @Ajasja In a slightly different situation such as If[condition, Return[x]]; 0.0 it does matter what comes after return. My suspicion is that it's not so easy for the compiler to tell these cases apart. It's not smart enough to be able to analyse your example and conclude that everything after the Return can be ignored. All it sees is that there are two potential exit points: one in Return and one after. They have different return types, and in fact one of them has an illegal return type (a symbol). $\endgroup$
    – Szabolcs
    Jun 22, 2012 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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