如何通过选择要添加的项来生成数组

时间:2014-07-01 13:25:06

标签: f#

我有以下数组

let evens = [| 
    for key in numbersDictionary.Keys -> 
        match numbersDictionary.[key] % 2
        | 0 -> Some(numbersDictionary.[key])
        | _ -> None |]

对于奇数,我确实有None的选项类型数组。如何调整上述语句,以便evens变为int[]而不是int option []而不是None

2 个答案:

答案 0 :(得分:6)

这应该有效:

let evens =
  numbersDictionary
  |> Seq.map (fun kvp -> kvp.Value)
  |> Seq.filter (fun v -> v % 2 = 0)
  |> Seq.toArray

更简单:

let evens =
  numbersDictionary.Values
  |> Seq.filter (fun v -> v % 2 = 0)
  |> Seq.toArray

或更接近您的问题:

let evens =
   [| for v in dict.Values do if v%2=0 then yield v |]

答案 1 :(得分:2)

您的代码等于:

let evens' = [| 
    for key in numbersDictionary.Keys do        
        yield //always yields into Array
            match numbersDictionary.[key] % 2 with 
            | 0 -> Some(numbersDictionary.[key])
            | _ -> None |]

->只写为do yield

现在通过移动匹配表达式中的yield,您可以获得所需的结果:

let evens'' = [| 
    for key in numbersDictionary.Keys do        
        match numbersDictionary.[key] % 2 with
        | 0 -> yield numbersDictionary.[key] //only yields this into Array
        | _ -> ()  |]