【问题标题】:how to do Array.tryFind with index?如何用索引做 Array.tryFind?
【发布时间】:2012-09-25 01:28:46
【问题描述】:

我想做的一个简单例子是

 Array.tryFind (fun elem index -> elem + index = 42) array1  //not valid

由于没有 breakcontinue,我发现即使在 for 循环中也很难手动完成

【问题讨论】:

    标签: f#


    【解决方案1】:

    与@gradbot 的回答类似,您可以沿着mapiiteri 的行定义一个模块函数,它适用于数组、列表和序列。

    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)
    

    【讨论】:

      【解决方案2】:

      每当我发现内置函数中缺少一些我需要的东西时,我都会添加它!我总是有一个名为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
      

      【讨论】:

        【解决方案3】:

        类似这样的内容(免责声明:在浏览器中输入 - 可能包含错误)

        array |> Seq.mapi (fun i el -> i + el) |> Seq.tryFind ((=)42)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-19
          • 2018-12-06
          • 2012-07-31
          • 2012-03-30
          相关资源
          最近更新 更多