Caml has the predefined type `a option ( `a means that it can be a variant of anything, just like `a list can be int list , a float list ...). This is actually a very simple type:
type `a option = Some of `a | None
Basically, a value of type `a option is either None or a value of `a is placed inside the field : it is not the same type as `a (which is why you get an error when you tell the compiler to treat it as int ).
You should probably think of it as an explicit way to deal with errors (more explicit than exceptions). Consider those (non-tail recursive, poorly written) functions:
let rec max_exn l = match l with | [] -> failwith "Empty list" | [x] -> x | x::tl -> max x (max_exn tl) let rec max_option l = match l with | [] -> None | [x] -> Some x | x::tl -> max x (max_option tl) (* max does work on options *)
The first is of type `a list -> `a , which allows the caller to forget about the empty case of the list. The second type is of type `a list -> `a option , which means that the caller will always handle the error.
In other words: None somewhat similar to null , except that you can always tell from the type of function whether it can return None (and if possible, the compiler forces you to handle this).
Jbeuh source share