OCaml Options
Many operations may or may not have a result: looking up a key, finding the first matching element, parsing a number. Other languages use null for "no result", which causes crashes when someone forgets to check. OCaml has no null. Instead it uses the option type:
type 'a option = None | Some of 'aAn int option is either None or Some n for some int n. The type system forces you to handle both cases before you can use the int.
let safe_divide a b = if b = 0 then None else Some (a / b)
let show = function
| Some q -> "result " ^ string_of_int q
| None -> "cannot divide by zero"
let () =
print_endline (show (safe_divide 20 4));
print_endline (show (safe_divide 1 0))result 5
cannot divide by zero
Where options come from
The standard library returns options from many "might fail" functions, usually those ending in _opt:
let print_opt_int label = function
| Some n -> Printf.printf "%s: Some %d\n" label n
| None -> Printf.printf "%s: None\n" label
let () =
print_opt_int "int_of_string_opt \"12\"" (int_of_string_opt "12");
print_opt_int "int_of_string_opt \"x\"" (int_of_string_opt "x");
print_opt_int "find_opt" (List.find_opt (fun n -> n > 3) [ 1; 5; 9 ]);
print_opt_int "assoc_opt" (List.assoc_opt "b" [ ("a", 1) ]);
print_opt_int "nth_opt" (List.nth_opt [ 10; 20 ] 1);
print_opt_int "index_opt" (String.index_opt "hello" 'l')int_of_string_opt "12": Some 12
int_of_string_opt "x": None
find_opt: Some 5
assoc_opt: None
nth_opt: Some 20
index_opt: Some 2
The Option module
Matching every time gets verbose. The Option module has helpers for the common cases:
| Function | Meaning |
|---|---|
Option.value o ~default |
the content, or default if None |
Option.map f o |
apply f inside Some, keep None |
Option.bind o f |
chain a step that itself returns an option |
Option.is_some, Option.is_none |
test |
Option.get o |
the content, raises Invalid_argument on None (avoid) |
Option.iter f o |
run f only for Some |
Option.to_list o |
[] or [x] |
let () =
let age = int_of_string_opt "41" and bad = int_of_string_opt "forty" in
Printf.printf "%d\n" (Option.value age ~default:0);
Printf.printf "%d\n" (Option.value bad ~default:0);
Printf.printf "%d\n" (Option.value (Option.map (fun a -> a + 1) age) ~default:(-1));
Printf.printf "%b %b\n" (Option.is_some age) (Option.is_none bad);
Option.iter (Printf.printf "age is %d\n") age;
Option.iter (Printf.printf "this never prints %d\n") bad41
0
42
true true
age is 41
Chaining steps with bind
When each step can fail, Option.bind runs the next step only if the previous one succeeded. Here we parse a "HH:MM" time string:
let parse_hour s = Option.bind (int_of_string_opt s) (fun h -> if h >= 0 && h < 24 then Some h else None)
let parse_minute s = Option.bind (int_of_string_opt s) (fun m -> if m >= 0 && m < 60 then Some m else None)
let parse_time s =
match String.split_on_char ':' s with
| [ h; m ] ->
Option.bind (parse_hour h) (fun hour ->
Option.map (fun minute -> (hour * 60) + minute) (parse_minute m))
| _ -> None
let () =
List.iter
(fun s ->
match parse_time s with
| Some mins -> Printf.printf "%-6s -> %d minutes after midnight\n" s mins
| None -> Printf.printf "%-6s -> invalid\n" s)
[ "09:30"; "23:59"; "24:00"; "7:5"; "noon" ]09:30 -> 570 minutes after midnight
23:59 -> 1439 minutes after midnight
24:00 -> invalid
7:5 -> 425 minutes after midnight
noon -> invalid
let* binding operators
Nested bind calls are hard to read. OCaml lets you define binding operators so the chain looks like ordinary lets:
let ( let* ) = Option.bind
let parse_range s =
match String.split_on_char '-' s with
| [ a; b ] ->
let* low = int_of_string_opt a in
let* high = int_of_string_opt b in
if low <= high then Some (low, high) else None
| _ -> None
let () =
List.iter
(fun s ->
match parse_range s with
| Some (lo, hi) -> Printf.printf "%s: %d values\n" s (hi - lo + 1)
| None -> Printf.printf "%s: invalid\n" s)
[ "3-7"; "10-2"; "a-9" ]3-7: 5 values
10-2: invalid
a-9: invalid
If any let* step produces None, the whole expression is None.
Tip: Use
Option.getandList.hdonly when you can prove the value exists. In nearly all other cases,matchorOption.value ~defaultis safer.
Test yourself
What is the type of Some "hi"?
stringstring optionoption string'a option
What does Option.map (fun x -> x * 2) None return?
0NoneSome 0- It raises an exception
What does Option.value (Some 3) ~default:10 return?
310Some 313