F# 如何使用索引执行Array.tryFind?
我想做的一个简单的例子是F# 如何使用索引执行Array.tryFind?,f#,F#,我想做的一个简单的例子是 Array.tryFind (fun elem index -> elem + index = 42) array1 //not valid 由于没有中断或继续,我发现即使在类似这样的for循环中也很难手动执行(免责声明:在浏览器中键入-可能包含错误) 与@gradbot的答案类似,您可以沿着mapi,iteri定义一个模块函数,该函数适用于数组、列表和序列 module Seq = let tryFindi fn seq = seq
Array.tryFind (fun elem index -> elem + index = 42) array1 //not valid
由于没有中断
或继续
,我发现即使在类似这样的for循环中也很难手动执行(免责声明:在浏览器中键入-可能包含错误)
与@gradbot的答案类似,您可以沿着
mapi
,iteri
定义一个模块函数,该函数适用于数组、列表和序列
module Seq =
let tryFindi fn seq =
seq |> Seq.mapi (fun i x -> i, x)
|> Seq.tryFind (fun (i, x) -> fn i x)
|> Option.map snd
// Usage
let res = [|1;1;40;4;2|] |> Seq.tryFindi (fun i el -> i + el = 42)
每当我从内置函数中发现我需要缺少的东西时,我就添加它!我总是有一个名为
Helpers.fs
的文件,其中保存了所有这些文件。一定要给它起个好名字
module Array =
let tryFindWithIndex fn (array : _[]) =
let rec find index =
if index < array.Length then
if fn array.[index] index then
Some(array.[index])
else
find (index + 1)
else
None
find 0
输出
Some 40
[|1;1;40;4;2|]
|> Array.tryFindWithIndex (fun elem index -> elem + index = 42)
|> printf "%A"
Some 40