F# Option equivalent of C#'s ?? operator

无人久伴 提交于 2019-12-19 05:04:58

问题


I am looking for a way to get the value of an F# option or use a default value if it is None. This seems so common I can't believe something predefined doesn't exist. Here is how I do it right now:

// val getOptionValue : Lazy<'a> -> Option<'a> -> 'a    
let getOptionValue (defaultValue : Lazy<_>) = function Some value -> value | None -> defaultValue.Force ()

I am (sort of) looking for the F# equivalent of the C# ?? operator:

string test = GetString() ?? "This will be used if the result of GetString() is null.";

No function in the Option module does what I think is a pretty basic task. What am I missing?


回答1:


You're looking for defaultArg [MSDN] ('T option -> 'T -> 'T).

It's often used to provide a default value for optional arguments:

type T(?arg) =
  member val Arg = defaultArg arg 0

let t1 = T(1) 
let t2 = T() //t2.Arg is 0



回答2:


You could easily create your own operator to do the same thing.

let (|?) = defaultArg

Your C# example would then become

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."

Here's a blog post that goes into a little more detail.

Edit: Nikon the Third had a much better implementation for the operator, so I updated it.



来源:https://stackoverflow.com/questions/12642554/f-option-equivalent-of-cs-operator

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