Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Last active January 22, 2023 05:48
Show Gist options
  • Select an option

  • Save jtpaasch/e65bc0de45b11ef2378b158cf9bcab97 to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/e65bc0de45b11ef2378b158cf9bcab97 to your computer and use it in GitHub Desktop.
Tutorial/cheat sheet for Jane Street Core's Option.

Option (from Jane Street Core)

Convert a value to an optional something:

let some_message = Option.some "goodbye";;

Suppose you have some data:

let datum_1 = Some "hello";;
let datum_2 = None;;

Check if it's none:

let is_none_1 = Option.is_none datum_1;;
let is_none_1 = Option.is_none datum_2;;

Check if it's something:

let is_some_1 = Option.is_none datum_1;;
let is_some_2 = Option.is_none datum_2;;

Get the value, or a default (if it's None):

let a = Option.value ~default:"goodbye" datum_1;;
let b = Option.value ~default:"goodbye" datum_2;;

Try

Get the value (or raise an exception):

let c = Option.value_exn datum_1;; (* Returns string "hello" *)

This would raise an exception, since datum_2 is None:

let d = Option.value_exn datum_2;; (* Raises exception *)

But you can try to get the value, and just return None if it raises an exception.

let e = Option.try_with (fun () -> Option.value_exn datum_2);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment