Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 587
Nikon the Third Avatar asked Sep 28 '12 15:09

Nikon the Third


People also ask

Facebook itu apa sih?

Facebook adalah media sosial dan layanan jejaring sosial online Amerika yang dimiliki oleh Meta Platforms.


1 Answers

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 
like image 66
Daniel Avatar answered Oct 14 '22 07:10

Daniel