Why can't Mathematica 9 compile this code?

x = {1};
Compile[{}, x[[1]]++;,
    {{x[[1]]++, _Integer}, {x[[1]], _Integer}}, CompilationTarget :> "C"][]

After printed message CompiledFunction::cflist, the value of x is (in my case) {2 + Compile`Variable$29510}.

Searching this site for "Compile Increment" found Faster list duplicate 'limiter', where an Increment is used in Compile and run correctly. I tried to fix my code using Block:

Compile[{}, Block[{x}, x = {1}; x[[1]]++; x[[1]] ], CompilationTarget :> "C"][]

Those also work.

x = {1}; Compile[{}, x[[1]] += 1;, CompilationTarget :> "C"][]

(replace ++ by +=1) or

x = {1}; Compile[{}, x[[1]]++;][]

(remove CompilationTarget -> "C" part)

This seems like a bug. Is that fixed in Mathematica 10?

  • $\begingroup$ All of these implementations that modify a global x call MainEvaluate. You can use CompilePrint to check that. $\endgroup$ – Karsten 7. Aug 16 '16 at 10:09
  • 1
    $\begingroup$ Seems like a bug to me. At first I thought it was exacerbated by your unusual external patterns (should be {{x, _Integer, 1}}, IMO). But actually changing that does not make a difference. There must be an error in the CCodeGenerator` package. $\endgroup$ – Oleksandr R. Aug 16 '16 at 10:14
  • $\begingroup$ Just a note that this problem persists at least until version 11.0.1. $\endgroup$ – Henrik Schumacher Jan 28 '18 at 9:59

Your Answer

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

Browse other questions tagged or ask your own question.