OCaml Option get

Matthew Hayes picture Matthew Hayes · Sep 5, 2012 · Viewed 21.1k times · Source

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, there is a get function of type 'a option -> 'a that does what I want. but when I type:

# let z = Some 3;;
val z : int option = Some 3
# get z;;
Error: Unbound value get
# Option.get z;;
Error: Unbound module Option

Why isnt this working?

Answer

Pascal Cuoq picture Pascal Cuoq · Sep 5, 2012

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