Mar*_*s F 6 arrays sorting collections f# exception
我有以下函数可以查找数组中的索引
let numbers_array = [| "1"; "2"; "3"|]
let findIndex arr elem = arr |> Array.findIndex ((=) elem)
let s = "123"
findIndex numbers_array (string s.[0]))
Run Code Online (Sandbox Code Playgroud)
但是如果我尝试跑步
findIndex numbers_array (string s.[10]))
它超出范围并抛出以下错误
System.Collections.Generic.KeyNotFoundException:在集合中找不到满足谓词的索引。
我怎样才能使我的函数不抛出异常,而是执行类似 printf 语句的操作?
我认为这很接近你想要的:
let findIndex arr elem =
match arr |> Array.tryFindIndex ((=) elem) with
| Some index -> index
| None ->
printfn "Not found"
-1
Run Code Online (Sandbox Code Playgroud)
它维护与现在相同的函数签名,并且如果未找到该元素,则会生成一条错误消息作为副作用。(请注意,在这种情况下该函数仍然必须返回 an int
,因此我选择了 -1。)