我正在寻找一种方法来获取F#选项的值,或者如果它是None,则使用默认值.这似乎很常见,我无法相信预定义的东西不存在.我现在就是这样做的:
// val getOptionValue : Lazy<'a> -> Option<'a> -> 'a
let getOptionValue (defaultValue : Lazy<_>) = function Some value -> value | None -> defaultValue.Force ()
Run Code Online (Sandbox Code Playgroud)
我(某种程度上)正在寻找与C#相当的F#?? 运营商:
string test = GetString() ?? "This will be used if the result of GetString() is null.";
Run Code Online (Sandbox Code Playgroud)
Option模块中没有任何功能可以完成我认为非常基本的任务.我错过了什么?
Dan*_*iel 36
您正在寻找defaultArg
[MSDN]('T option -> 'T -> 'T
).
它通常用于为可选参数提供默认值:
type T(?arg) =
member val Arg = defaultArg arg 0
let t1 = T(1)
let t2 = T() //t2.Arg is 0
Run Code Online (Sandbox Code Playgroud)
Tro*_*haw 14
您可以轻松创建自己的运算符来执行相同的操作.
let (|?) = defaultArg
Run Code Online (Sandbox Code Playgroud)
然后你的C#例子就会变成
let getString() = (None:string option)
let test = getString() |? "This will be used if the result of getString() is None.";;
val getString : unit -> string option
val test : string = "This will be used if the result of getString() is None."
Run Code Online (Sandbox Code Playgroud)
这是一篇博文,详细介绍了一些细节.
编辑:Nikon the Third为操作员提供了更好的实现,因此我对其进行了更新.