Structs in OCaml
The struct
type in the code has name
and age
fields.
OCaml uses record
types for a similar purpose.
In this example, the person
type is a record type, and new_person
is a function that creates a new person
record with the given name.
Here’s the full source code translated to OCaml:
Structs#
Explanation:
OCaml’s record types are typed collections of fields. They are useful for grouping data together to form records.
OCaml Code:
Explanation:
- The
person
record type has name
and age
fields. - The
new_person
function constructs a new person
record with the given name and an age of 42. - A new record is created and its fields are printed using
Printf.printf
. - Naming fields when initializing a record.
- Omitting fields will result in zero-valued fields.
- Accessing and updating record fields directly.
- Creating and using an anonymous record type.
To run the program, put the code in a file (e.g., structs.ml
) and use the OCaml compiler: