# Why does compiled function give different results than uncompiled version?

I have a simple function that I've written as both a pure function and a compiled pure function, but the compiled version produces different results, suggesting either I don't know how to get it to work with Compile or that Compile has some limitations I didn't know about. I intend to give the function two arguments, the first is a single real number, and the second is a list of integers.

fun = Apply[Times, #1 - Range[#2], {1}] &;

fc = Compile[
{{value, _Real},
{counts, _Integer, 1}},
Apply[Times, #1 - Range[#2], {1}] &[value, counts]
];

fun[5, {1, 2, 3}]
fc[5, {1, 2, 3}]


The results I obtain are

{4, 12, 24}

{4., 3., 2.}

The results I want to obtain are those produced by the non-compiled function.

I know I could rewrite the function as follows to produce the results that I want (thanks, @glS).

fcV2 = Compile[
{{value, _Real},
{counts, _Integer, 1}},
Apply[Times, value - Range@# ] & /@ counts
];


Why doesn't my first attempt at a compiled function work as expected? Is there a way to fix it without explicit mapping?

• (1) You won't be able to do it because Range[{1,2,3}] (uncompiled) does not produce a rectangular array. (2) Inside Compile[], Range[{1,2,3}] produces {1,2,3}. – Michael E2 Jul 20 '17 at 21:08

Compare:

Range[{1, 2, 3}]

Compile[{{c, _Integer, 1}}, Range[c]][{1, 2, 3}]


{{1}, {1, 2}, {1, 2, 3}}

{1, 2, 3}

This is related to the fact that Compile does not work with ragged arrays, which is what Range[{1,2,3}] returns.

• Do you know why Range[{1,2,3}] produces {1,2,3} instead of, say, a call to MainEvaluate? It seems odd that it produces a different result in the two contexts. – Michael E2 Jul 20 '17 at 21:09
• I think it's worth reporting to Wolfram. – Carl Woll Jul 20 '17 at 21:11
• I reported it to Wolfram Technical Support, asking whether "such behavior is intentional, or whether Wolfram would prefer to modify [it]." The response I received is: "I would say that this is peculiar, but not entirely unexpected behavior on the part of Compile; as you have said yourself, compiled functions are not able to take in, deal with, or produce ragged arrays. Therefore, if you expect that your uncompiled code would generate ragged arrays in the course of its evaluation, some modification will be needed if you want to write a compiled version of it." – FalafelPita Aug 7 '17 at 19:34