I\'m new to OCaml, I\'m trying to understand how you\'re supposed to get the value from an \'a option. According to the doc at http://ocaml-lib.sourceforge.net/doc/Option.html,
You should listen to the above posters advice regarding type safety but also be aware that unsafe function such as Option.get (which is available in batteries btw) are usually suffixed with exn. If you're curious this is how Option.get or Option.get_exn could be implemented then:
let get_exn = function
| Some x -> x
| None -> raise (Invalid_argument "Option.get")
The usual way to do this is with pattern matching.
# let x = Some 4;;
val x : int option = Some 4
# match x with
| None -> Printf.printf "saw nothing at all\n"
| Some v -> Printf.printf "saw %d\n" v;;
saw 4
- : unit = ()
You can write your own get function (though you have to decide what you want to do when the value is None).
The traditional way to obtain the value inside any kind of constructor in OCaml is with pattern-matching. Pattern-matching is the part of OCaml that may be most different from what you have already seen in other languages, so I would recommend that you do not just write programs the way you are used to (for instance circumventing the problem with ocaml-lib) but instead try it and see if you like it.
let contents =
match z with
Some c -> c;;
Variable contents
is assigned 3
, but you get a warning:
Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None
In the general case, you won't know that the expression you want to look inside is necessarily a Some c
. The reason an option type was chosen is usually that sometimes that value can be None
. Here the compiler is reminding you that you are not handling one of the possible cases.
You can pattern-match “in depth” and the compiler will still check for exhaustivity. Consider this function that takes an (int option) option
:
let f x =
match x with
Some (Some c) -> c
| None -> 0
;;
Here you forgot the case Some (None)
and the compiler tells you so:
Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Some None