Methods in OCaml
OCaml supports methods defined on record types, which are similar to structs in other languages.
To run the program:
In OCaml, we define functions that operate on our rect
type, rather than methods that are attached to the type. The area
and perim
functions take a rect
as their first argument.
OCaml doesn’t have the concept of pointer and value receivers like some other languages. Instead, all values are immutable by default. If you need to modify a value, you would typically create a new value or use a mutable reference.
In the example above, we create a reference rref
to demonstrate a similar concept to using a pointer in other languages. However, in idiomatic OCaml, you would typically just pass the value directly.
Next, we’ll look at OCaml’s mechanism for grouping and naming related sets of functions: modules and signatures.