(** Functions to handle the option type. *) (** Apply f to the Some value *) let map (f : 'a -> 'b) (a : 'a option) : 'b option = match a with None -> None | Some x -> Some (f x) (** Like map, but use when f returns an option. With this you can turn Some's to None's. *) let apply (f : 'a -> 'b option) (a : 'a option) : 'b option = match a with None -> None | Some x -> f x (** Return the Some value, or raise an exception *) let get = function Some x -> x | None -> raise (Invalid_argument "Option.get") (** Like get, but provide a default value for None instead of raising an exception. *) let set d = function Some x -> x | None -> d (** Commonly used combination of set and map *) let setmap d f o = set d (map f o) (** Turn selected Somes into Nones *) let zap pred = function Some x when pred x -> None | x -> x (** Wrap up a compare function so that None values sort later *) let compare compare a b = match a, b with None, None -> 0 | None, _ -> 1 | _, None -> -1 | Some a, Some b -> compare a b (** Turn option into a boolean value *) let pred = function Some x -> true | None -> false (** Filter the Nones out of an option list and retrieve the Some value. *) let filter (lst : 'a option list) = List.map get (List.filter pred lst) let to_string string_of x = set "None" (map string_of x)