模式匹配守卫与DateTime.TryParseExact?

时间:2014-11-07 20:22:46

标签: f# guard-clause

如何保护DateTime.TryParseExact(并在可能的情况下获取解析后的值)?以下代码不起作用。

[<EntryPoint>]
let main args =
    let argList = args |> List.ofSeq
    match argList with
    | "aaa" :: [] -> aaa.main "aaa"
    | "bbb" :: [] -> bbb.main "bbb"
    | "ccc" :: yyyymm :: [] when DateTime.TryParseExact
              (yyyymm, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None)-> 
        ccc.main "ccc" yyyymm

1 个答案:

答案 0 :(得分:7)

您可以使用mutable

let mutable dt = Unchecked.defaultof<_>
match argList with
| "ccc" :: yyyymm :: [] when 
    DateTime.TryParseExact(yyyymm, 
                           "yyyyMM", 
                           CultureInfo.InvariantCulture, 
                           DateTimeStyles.None, 
                           &dt) -> ...

但是一个活跃的模式使得比赛更加清晰:

let (|DateTimeExact|_|) (format: string) s =
    match DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None) with
    | true, d -> Some d
    | _ -> None

match argList with
| "ccc" :: DateTimeExact "yyyyMM" yyyymm :: [] -> ...
相关问题