In functional programming languages like F#
null
values are considered
potentially harmful and poor style (non-idiomatic).
Consider this C#
code:
string x = SomeFunction ();
int l = x.Length;
x.Length
will throw if x
is null
let's add protection:
string x = SomeFunction ();
int l = x != null ? x.Length : 0;
Or:
string x = SomeFunction () ?? "";
int l = x.Length;
Or:
string x = SomeFunction ();
int l = x?.Length;
In idiomatic F#
null
values aren't used so our code looks like this:
let x = SomeFunction ()
let l = x.Length
However, sometimes there's a need for representing empty or invalid values. Then
we can use Option<'T>
:
let SomeFunction () : string option = ...
SomeFunction
either returns Some
string
value or None
. We extract the
string
value using pattern matching
let v =
match SomeFunction () with
| Some x -> x.Length
| None -> 0
The reason this code is less fragile than:
string x = SomeFunction ();
int l = x.Length;
Is because we can't call Length
on a string option
. We need to extract the
string
value using pattern matching and by doing so we are guaranteed that the
string
value is safe to use.