F#: shortest way to convert a string option to a string

為{幸葍}努か 提交于 2019-12-05 14:29:07

You can also use the function defaultArg input "" which in your code that uses forward pipe would be:

input |> fun s -> defaultArg s ""

Here's another way of writing the same but without the lambda:

input |> defaultArg <| ""

It would be better if we had a version in the F# core with the arguments flipped. Still I think this is the shortest way without relaying in other libraries or user defined functions.

UPDATE

Now in F# 4.1 FSharp.Core provides Option.defaultValue which is the same but with arguments flipped, so now you can simply write:

Option.defaultValue "" input

Which is pipe-forward friendly:

input |> Option.defaultValue ""

The obvious way is to write yourself a function to do it, and if you put it in an Option module, you won't even notice it's not part of the core library:

module Option =
    let defaultTo defValue opt = 
        match opt with
        | Some x -> x
        | None -> defValue

Then use it like this:

input |> Option.defaultTo ""

The NuGet package FSharpX.Extras has Option.getOrElse which can be composed nicely.

let x = stringOption |> Option.getOrElse ""

The best solution I found so far is input |> Option.fold (+) "".

...which is just a shortened version of input |> Option.fold (fun s t -> s + t) "".

I suspect that it's the shortest I'll get, but I'd like to hear if there are other short ways of doing this that would be easier to understand by non-functional programmers.

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