F# Array.FindIndex 异常处理

时间:2021-01-24 18:33:13

标签: arrays sorting exception collections f#

我有以下函数可以在数组中找到索引

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

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

但是如果我尝试运行

findIndex numbers_array (string s.[10]))

它越界并抛出以下错误

System.Collections.Generic.KeyNotFoundException:在集合中找不到满足谓词的索引。

我怎样才能让我的函数不抛出异常,而是做一些类似于 printf 语句的事情?

1 个答案:

答案 0 :(得分:3)

我认为这与您想要的很接近:

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

它保持您现在拥有的相同函数签名,并在未找到元素时生成错误消息作为副作用。 (请注意,在这种情况下,该函数仍必须返回 int,因此我选择了 -1。)