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:

type person = { name : string; mutable age : int }

let new_person name =
  let p = { name = name; age = 42 } in
  p

let () =
  (* This syntax creates a new record *)
  Printf.printf "%s\n" (match { name = "Bob"; age = 20 } with person -> Printf.sprintf "%s %d" person.name person.age);
  
  (* You can name the fields when initializing a record *)
  Printf.printf "%s\n" (match { name = "Alice"; age = 30 } with person -> Printf.sprintf "%s %d" person.name person.age);
  
  (* Omitted fields will be zero-valued *)
  Printf.printf "%s\n" (match { name = "Fred"; age = 0 } with person -> Printf.sprintf "%s %d" person.name person.age);
  
  (* Using a mutable record field to update a field's value *)
  let s = { name = "Sean"; age = 50 } in
  Printf.printf "%s\n" s.name;
  
  (* Access record fields *)
  Printf.printf "%d\n" s.age;
  
  (* Record fields are mutable so their values can be updated *)
  let sp = s in
  sp.age <- 51;
  Printf.printf "%d\n" s.age;
  
  (* Creating an anonymous record type *)
  let dog = { name = "Rex"; isGood = true } in
  Printf.printf "%s %s\n" (dog.name) (string_of_bool dog.isGood)

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:

$ ocamlc -o structs structs.ml
$ ./structs
Bob 20
Alice 30
Fred 0
Sean
50
51
Rex true