Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Array.tryFindIndex start search from an index

Tags:

f#

I wonder if there's a cheap(performance wise) option to search an index of array element which meets certain criteria starting from an index?

Array.tryFindIndex method doesn't have an argument startIndex. I could do Array.skip(n) and then search there but it seems expensive to create an array just for search. How do I do this?

I looked List also doesn't have that argument. Do I have to use while ... do? Is there a nicer way?

like image 228
user1325696 Avatar asked Sep 04 '25 17:09

user1325696


1 Answers

The base libraries try to provide functions for your convenience but they cannot possibly anticipate all use cases. Nothing wrong with writing your own if need be:

module Array =
    let tryFindIndexFrom i p (a : _ []) =
        let rec loop k =
            if k >= a.Length then None
            elif p a.[k] then Some k
            else loop (k + 1)
        if i < 0 then None else loop i

EDIT: p is the predicate testing the array elements. tryFindIndexFrom has the same signature as tryFindIndex but with the starting index added as first parameter.

EDIT 2: Added test for k < 0 for fool-proof usage.

EDIT 3: Moved test for k < 0 out of the loop as it needs to be checked only once.

like image 169
dumetrulo Avatar answered Sep 07 '25 17:09

dumetrulo