Jane Street OCaml Challenge: Tuples and Pairs

Tuples

A tuple is a fixed-size collection of values, potentially of different types.

type int_and_string_and_char = int * string * char let example : int_and_string_and_char = 5, "hello", 'A' let i, s, c = example let () = assert (i = 5); assert (String.(=) s "hello"); assert (Char.(=) c 'A')

Working with Coordinates

type coordinate = int * int let add coord1 coord2 = failwith "For you to implement"

Generalizing with Pairs

We can define a generic pair type:

type 'a pair = 'a * 'a let int_pair : int pair = 5, 7 let string_pair : string pair = "foo", "bar" let nested_char_pair : char pair pair = ('a', 'b'), ('c', 'd')

Your Turn

Write generic functions to extract values from a pair:

let first pair = failwith "For you to implement" let second pair = failwith "For you to implement"

Tests

let%test "Testing add..." = [%compare.equal: int * int] (4, 7) (add (5, 3) (-1, 4)) let%test "Testing first..." = String.(=) "foo" (first ("foo", "bar")) let%test "Testing second..." = Char.(=) 'b' (second ('a', 'b'))