You could also implement the short-circuiting one recursively:

function findocc(f, A, i)
    i == 1 && return findfirst(f, A)
    findnext(f, A, findocc(f, A, i - 1) + 1)
end

julia> A = [1:10...] 
10-element Array{Int64,1}: 
 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 

julia> findocc(x->iseven(x), A, 3) 
6 

julia> findocc(x->iseven(x), A, 5) 
10 

julia> findocc(x->iseven(x), A, 6) 
0



On Friday, July 17, 2015 at 10:07:47 AM UTC-4, David Gold wrote:
>
> If you don't care about short-circuiting after finding the nth occurrence 
> you could of course just do `find(f, A)[n]`.
>
> On Friday, July 17, 2015 at 10:00:43 AM UTC-4, Pontus Stenetorp wrote:
>>
>> Everyone, 
>>
>> I just recently needed to find the index of the n-th occurrence of a 
>> predicate an Array and was a bit surprised that there was not a 
>> convenience function in Base.  Rolling one on your own is simple, but 
>> I somehow expected to find something in Base to get the same 
>> functionality. 
>>
>>     function findocc(testf::Function, A, n) 
>>         i = 0 
>>         for _ in 1:n 
>>             i = findnext(testf, A, i + 1) 
>>             i != 0 || return 0 
>>         end 
>>         return i 
>>     end 
>>
>> Am I perhaps missing something that is already supported in Base? [1] 
>> If not, I may consider yet another small pull request.  But as always 
>> with these small convenience functions I fear that I am missing 
>> something obvious that already supports the same functionality. 
>>
>>     Pontus 
>>
>> [1]: 
>> http://julia.readthedocs.org/en/latest/stdlib/arrays/?highlight=find#Base.find
>>  
>>
>

Reply via email to