【发布时间】:2012-09-25 01:28:46
【问题描述】:
我想做的一个简单例子是
Array.tryFind (fun elem index -> elem + index = 42) array1 //not valid
由于没有 break 或 continue,我发现即使在 for 循环中也很难手动完成
【问题讨论】:
标签: f#
我想做的一个简单例子是
Array.tryFind (fun elem index -> elem + index = 42) array1 //not valid
由于没有 break 或 continue,我发现即使在 for 循环中也很难手动完成
【问题讨论】:
标签: f#
与@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
使用示例。
[|1;1;40;4;2|]
|> Array.tryFindWithIndex (fun elem index -> elem + index = 42)
|> printf "%A"
输出
Some 40
【讨论】:
类似这样的内容(免责声明:在浏览器中输入 - 可能包含错误)
array |> Seq.mapi (fun i el -> i + el) |> Seq.tryFind ((=)42)
【讨论】: