去掉过滤的中间选项值?

Remove the intermediate option value for filtering?

下面的代码returns T seq。引入的选项值 c'' 仅用于过滤,函数需要获取 c''.Value 以获得 return 值。

是不是另一种写法,不需要创建中间选项值和两个映射?

type T = { A: string; B: string; C: DateTime } // Maybe more fields
let f x =
  x
  |> Seq.map(fun y -> 
    let a = ...
    let b = ....
    let c' = .... // Some complex code
    let c'' = match c' with DateTimeExact "d" c -> Some c | _ -> None
    a, b, c''
  |> Seq.filter(fun (_, _, c'') -> match c'' with | None -> false | _ -> true
  |> Seq.map(fun (a, b, c'') -> { A = a; B = b; C = c''.Value }

Seq.choose随心所欲

它允许您从 't -> 'u option 应用映射函数并过滤掉 return None

的元素

我可能会使用序列计算表达式:

let f xs = seq {
  for x in xs do
      let a = ...
      let b = ....
      let c' = .... // Some complex code
      match c' with 
        | DateTimeExact "d" c -> 
            yield { A = a; B = b; C = c }
        | _ -> 
            ()
}