[英]What is the correct way to call DateTime.TryParse from F#?
從 F# 調用 DateTime.TryParse 的正確方法是什么? 我正在嘗試從 F# Interactive 測試一些代碼,但我不知道如何通過 ref 將可變的 DateTime 傳遞到第二個參數中。 F# 中的輸入/輸出/引用語法是什么?
這是我正在查看的方法簽名: http : //msdn.microsoft.com/en-us/library/ch92fbc1.aspx?cs-save-lang=1&cs-lang=fsharp#code-snippet-1
如果你真的需要通過引用傳遞一個可變的DateTime
,那么Chris的答案是正確的。 然而,在很多F#更地道使用編譯器的治療后才能out
參數tupled返回值:
let couldParse, parsedDate = System.DateTime.TryParse("11/27/2012")
這里,第一個值是bool
返回值,而第二個值是指定的out參數。
以下是在F#中執行DateTime.TryParse的方法:
let mutable dt2 = System.DateTime.Now
let b2 = System.DateTime.TryParse("12-20-04 12:21:00", &dt2)
其中&
運算符找到dt2的內存地址以修改引用。
這是關於F#參數syntaxt的一些附加信息 。
僅僅為了完整性,另一種選擇是使用ref cell,例如
let d = ref System.DateTime.MinValue
if (System.DateTime.TryParse("1/1/1", d)) then
// ...
我找到了另外一種方式,它似乎更具功能性(來自https://stackoverflow.com/a/4950763/1349649 )
match System.DateTime.TryParse "1-1-2011" with
| true, date -> printfn "Success: %A" date
| false, _ -> printfn "Failed!"
不幸的是,我找不到任何有關它如何工作的信息。
我有一個我喜歡包含在我所有項目中的輔助模塊。 我收集這樣的東西,將所有命令式 -> 功能轉換放在一個地方以供重用:
module helper =
//if some, unwrap input and call fun
let inline ( |>- ) x f = Option.bind f x //bind f x
//if some, unwrap input, call fun, and wrap output
let inline ( |>-+ ) x f = Option.map f x
module dateTime =
let tryParse (input: string) : DateTime option =
let mutable dt = DateTime.Now
if DateTime.TryParse(input, &dt) then Some dt else None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.