type student = {
name : string;
year : int; (* graduation year*)
}
type student = { name : string; year : int; }
We can then create values of the record type
let rbg = {
name = "Ruth Bader";
year = 1954;
}
val rbg : student = {name = "Ruth Bader"; year = 1954}
Fun fact! If we want to include code we've written in a file in utop via the
usedirective:#use "filename.ml".
We can access a field in a record with the . operator
rbg.name;;
- : string = "Ruth Bader"
Another basic kind of data type is a tuple. They're like records; however, they're unnamed.
(10, 10, "am");;
- : int * int * string = (10, 10, "am")
This is a tuple with 3 values. We can even give this tuple type a name.
type time = int * int * string;;
type time = int * int * string
(10, 10, "am");;
- : int * int * string = (10, 10, "am")
let t : time = (10, 10, "am");;
val t : time = (10, 10, "am")
These two values ([6] and [7]) are the same.
type point = float * float;;
type point = float * float
let p = (5., 3.5);;
val p : float * float = (5., 3.5)
Say we wanted to access the elements of this tuple. OCaml defines the fst and snd methods that get the first and second items from a tuple respectively.
fst;;
- : 'a * 'b -> 'a = <fun>
snd;;
- : 'a * 'b -> 'b = <fun>
fst p;;
- : float = 5.
snd p;;
- : float = 3.5
It's important to note that these only work on pairs. OCaml will throw an error if we don't have a pair
fst t;; (* our time tuple from earlier *)
File "[14]", line 1, characters 4-5:
1 | fst t;; (* our time tuple from earlier *)
^
Error: This expression has type time = int * int * string
but an expression was expected of type 'a * 'b