我正在编写一些代码来处理大型数据文件。如果该字段为空,则CSV TypeProvider将返回NaN给定值。我有很多字段,因此如果我编写一个辅助函数来检查该NaN并返回None,则它更干净。不知道如何编写一个更通用的辅助函数,我想到了:
let (!?) x = if Double.IsNaN(x) then None else Some (decimal x)
let (!?) (x, y) =
match (x, y) with
| (x, y) when not(Double.IsNaN(x)) && not (Double.IsNaN(y)) -> Some (decimal x, decimal y)
| (_, _) -> None
[不幸的是,我对运算符重载的尝试无法正常工作,并且复制代码也不是很好。新手问,有更好的方法吗?
((我知道类似PreferOptionals之类的东西,但我需要有选择地这样做)
您需要使它们成为封闭类型的静态成员:
open System
type T = T with
static member ($) (T, x) = if Double.IsNaN(x) then None else Some (decimal x)
static member ($) (T,(x, y)) =
match (x, y) with
| (x, y) when not(Double.IsNaN(x)) && not (Double.IsNaN(y)) -> Some (decimal x, decimal y)
| (_, _) -> None
let inline parse (x) = T $ x
let a = parse (1. , 2.)
// val a : (decimal * decimal) option = Some (1M, 2M)
let b = parse (1.)
// val b : decimal option = Some 1M
还请注意,最好使用二进制运算符来发送封装类型,这样可以延迟重载解析。