Question

I have this array

let myArray = [1;2;3;5;2;7]

I want to get the number 4, not 1 for Seq.FindIndex(fun x -> x=2) myArray I can reverse the array. However I was hoping there is a Seq.FindIndexReverse function....

Any ideas?

Was it helpful?

Solution 2

As not very "functional" but effective solution you can use Array.LastIndexOf

OTHER TIPS

If reversing the array doesn't cut it for you, how about you write one yourself?

let findLastIndex f arr = 
    let rec inner f arr idx = 
      match idx with
      | _ when idx >= 0 ->
         if f (arr.[idx])
            then Some idx
            else inner arr f (idx - 1)
      | _ -> None
    inner f arr (Array.length arr - 1) 

Didn't test it, but something like this should work.

By the way, you gave a list, not an array in your example. You define array literals with [| |].

There's no built-in function for that, but you can combine your way to it easily:

[1;2;3;5;2;7] |> List.rev |> List.findIndex (fun x -> x = 2)

However, this still returns 1, because the second-to-last element is also 1.

BTW, your list is a list, not an array, but it would be similar for arrays:

[|1;2;3;5;2;7|] |> Array.rev |> Array.findIndex (fun x -> x = 2)

This is quite late, but it might be useful for anyone else coming across this:

In F# 4.0 a method called findIndexBack was added for Array, List and Seq. This should return 4 for your function.

It's not documented on MSDN/GitHub, but the commit is on GitHub and it appears in Visual Studio's Intellisense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top