[英]What is the correct way to call DateTime.TryParse from F#?
What is the correct way to call DateTime.TryParse from F#?从 F# 调用 DateTime.TryParse 的正确方法是什么? I am trying to test some code from F# interactive and I can't figure out how to pass a mutable DateTime into the second argument by ref.
我正在尝试从 F# Interactive 测试一些代码,但我不知道如何通过 ref 将可变的 DateTime 传递到第二个参数中。 What is the in/out/ref syntax in F#?
F# 中的输入/输出/引用语法是什么?
This is the method signature I'm looking at: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx?cs-save-lang=1&cs-lang=fsharp#code-snippet-1这是我正在查看的方法签名: http : //msdn.microsoft.com/en-us/library/ch92fbc1.aspx?cs-save-lang=1&cs-lang=fsharp#code-snippet-1
Chris's answer is correct if you really need to pass a mutable DateTime
by reference. 如果你真的需要通过引用传递一个可变的
DateTime
,那么Chris的答案是正确的。 However, it is much more idiomatic in F# to use the compiler's ability to treat trailing out
parameters as tupled return values: 然而,在很多F#更地道使用编译器的治疗后才能
out
参数tupled返回值:
let couldParse, parsedDate = System.DateTime.TryParse("11/27/2012")
Here, the first value is the bool
return value, while the second is the assigned out parameter. 这里,第一个值是
bool
返回值,而第二个值是指定的out参数。
Here's how to execute DateTime.TryParse in F#: 以下是在F#中执行DateTime.TryParse的方法:
let mutable dt2 = System.DateTime.Now
let b2 = System.DateTime.TryParse("12-20-04 12:21:00", &dt2)
Where the &
operator finds the memory address of dt2 in order to modify the reference. 其中
&
运算符找到dt2的内存地址以修改引用。
Here's some additional information on F# parameter syntaxt. 这是关于F#参数syntaxt的一些附加信息 。
Just for the sake of completeness, yet another option is to use ref cells, eg 仅仅为了完整性,另一种选择是使用ref cell,例如
let d = ref System.DateTime.MinValue
if (System.DateTime.TryParse("1/1/1", d)) then
// ...
I've found one more way, it seems more functional style (from https://stackoverflow.com/a/4950763/1349649 ) 我找到了另外一种方式,它似乎更具功能性(来自https://stackoverflow.com/a/4950763/1349649 )
match System.DateTime.TryParse "1-1-2011" with
| true, date -> printfn "Success: %A" date
| false, _ -> printfn "Failed!"
Unfirtunately, I can't find any information about how it works. 不幸的是,我找不到任何有关它如何工作的信息。
I have a helper module I like to include in all my projects.我有一个我喜欢包含在我所有项目中的辅助模块。 I collect things like this, putting all the imperative -> functional conversions in one place for reuse:
我收集这样的东西,将所有命令式 -> 功能转换放在一个地方以供重用:
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.