Pattern match guard with DateTime.TryParseExact?

百般思念 提交于 2019-12-13 00:41:20

问题


How to guard with DateTime.TryParseExact (and get the parsed value if possible)? The following code doesn't work.

[<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:


You can use a mutable:

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

But an active pattern makes the match much clearer:

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 :: [] -> ...


来源:https://stackoverflow.com/questions/26809483/pattern-match-guard-with-datetime-tryparseexact

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!