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

前端 未结 2 1751
梦谈多话
梦谈多话 2021-01-07 19:38

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

2条回答
  •  忘掉有多难
    2021-01-07 20:33

    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.

提交回复
热议问题