F# Array.FindIndex exception handling

Viewed 152

I have the following function that finds the Index in an Array

let numbers_array = [| "1"; "2"; "3"|]
let findIndex arr elem = arr |> Array.findIndex ((=) elem)

let s = "123"
findIndex numbers_array (string s.[0]))

However if i try to run

findIndex numbers_array (string s.[10]))

it is out of bounds and throws the following error

System.Collections.Generic.KeyNotFoundException: An index satisfying the predicate was not found in the collection.

How can i make my function so instead of throwing the exception it does something instead like a printf statement?

1 Answers

I think this is close to what you want:

let findIndex arr elem =
    match arr |> Array.tryFindIndex ((=) elem) with
        | Some index -> index
        | None ->
            printfn "Not found"
            -1

It maintains the same function signature you have now, and generates an error message as a side-effect if the element isn't found. (Note that the function still has to return an int in this case, so I've chosen -1.)

Related