What is the F# equivalent of string.IsNullOrEmpty()?

Viewed 830

Given the following record in F#:

type Model =
   { Text: string option }

What is the F# equivalent of C#'s,

    string.IsNullOrEmpty(Model.Text)

TIA

3 Answers

Assuming you want to treat a None value as null or empty you can use Option.fold:

let m = { Text = Some "label" }
m.Text |> Option.fold (fun _ s -> String.IsNullOrEmpty(s)) true

a drawback of using fold is the ignored accumulator parameter in the accumulator function. In this case you just need a function to apply in the case of Some and a default value to use if the option is None e.g.

let getOr ifNone f = function
    | None -> ifNone
    | Some(x) -> f x

then you can use

m.Text |> getOr true String.IsNullOrEmpty

Lees answer is probably the most functionally idiomatic i.e. when you want to process a data type, you can squash it into an answer using fold. But note that you can drop the "s", to make it

m.Text |> Option.fold (fun _ -> String.IsNullOrEmpty) true

if folding isnt something that you are yet at ease with then a more set oriented version would be, "are all of them empty?" (if there are none, then they are)

m.Text |> Option.forall (fun s -> String.IsNullOrEmpty s)

or in short hand

m.Text |> Option.forall String.IsNullOrEmpty

(I'd personally use this one)

The Option.toObj function converts an option containing a reference type to a nullable object. A None will be converted to null. It's quite useful for interop with APIs expecting nulls:

model.Text |> Option.toObj |> String.IsNullOrEmpty
Related