f sharp option code example

Example: f# option

Option is a union type built into F# and is used to indicate that a return
may have no associated value. This is commonly used to avoid the use of nulls
and explicitly state when a value may be "nullable" in code.

//definition
type Option<'a> =
  | Some of 'a
  | None
 
//example
let findOption v = List.tryFind (fun x -> x = v)
findOption 3 [1;2;3;4] //Some 3
findOption 10 [1;2;3;4] //None

The value can be retrieved through pattern matching, forcing the None case to be
handled as well.

match findOption 3 [1;2;3;4] with
| Some v -> v
| None -> -1