2012-09-24 24 views
2

的,我想怎麼做一個簡單的例子是如何做帶索引的Array.tryFind?

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

由於沒有breakcontinue,我覺得很難做手工,甚至在一個for循環

回答

4

與@ gradbot的答案類似,你可以沿着mapi行定義模塊功能,iteri這窩ks在數組,列表和序列上。

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

像這樣(免責聲明:打字瀏覽器 - 可能含有錯誤)

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

每當我找到一些我需要從內置函數中丟失的東西時,我只是將其添加!我總是有一個名爲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 
相關問題