# How to use FirstPosition in compiled function

I am trying to compile something similar to the following:

test = Compile[{{data, _Real, 1}},
First@FirstPosition[data, _?(# > 0 &)]]


However I get the following error, which I don't understand:

Compile::part: Part specification FirstPosition[data,_?(#1>0&)][[1]] cannot be compiled since the argument is not a tensor of sufficient rank. Evaluation will use the uncompiled function.


Is there a way to make this work?

• The function FirstPosition simply will not compile to lower level code, so the only way to do this, is to write your own iterative loop from scratch. A simple Do loop with a Break should suffice. – Sjoerd Smit Dec 6 '19 at 22:25
• Or a While loop... – Henrik Schumacher Dec 7 '19 at 6:08

As Sjoerd notes, you can't Compile pattern matching functions like FirstPosition. On the other hand, this will work for what you're trying to do:

test =
Compile[{{data, _Real, 1}},
MapIndexed[
(If[# > 0, Return[#2[[1]]]]; 1) &,
data
];
-1
];

test@RandomReal[{-1, .01}, 100]

-1

test@RandomReal[{-1, .01}, 100]

46