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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With