问题
The objective is to convert a string option
that comes out of some nicely typed computation to a plain string
that can then be passed to the UI/printf
/URL/other things that just want a string and know nothing of option types. None
should just become the empty string.
The obvious way is to do a match
or an if
on the input:
input |> fun s -> fun s -> match s with | Some v -> v | _ -> ""
or
input |> fun s -> if s.IsSome then s.Value else ""
but while still being one-liners, these still take up quite a lot of line space. I was hoping to find the shortest possible method for doing this.
回答1:
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 ""
回答2:
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 ""
回答3:
The NuGet package FSharpX.Extras has Option.getOrElse which can be composed nicely.
let x = stringOption |> Option.getOrElse ""
回答4:
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.
来源:https://stackoverflow.com/questions/39436406/f-shortest-way-to-convert-a-string-option-to-a-string