Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

tostring

f#

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.

like image 614
mt99 Avatar asked Sep 11 '16 13:09

mt99


3 Answers

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 ""
like image 151
Gus Avatar answered Nov 20 '22 21:11

Gus


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 ""
like image 25
scrwtp Avatar answered Nov 20 '22 21:11

scrwtp


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

let x = stringOption |> Option.getOrElse ""

like image 2
marklam Avatar answered Nov 20 '22 22:11

marklam