Objects inside objects in OCaml

I am trying to figure out how I can parameterize OCaml objects with other objects. In particular, I want to create an object linkthat contains a forward object nodeand a reverse object node, and I want to be able to create a link by saying something like:

let link1 = new link node_behind node_ahead;;
+5
source share
1 answer

Objects are normal expressions in OCaml, so you can pass them as arguments to the constructor of objects and classes. See the section in the OCaml manual for a deeper explanation.

So, for example, you can write:

class node (name : string) = object
  method name = name
end

class link (previous : node) (next : node) = object
  method previous = previous
  method next = next
end

let () =
  let n1 = new node "n1" in
  let n2 = new node "n2" in
  let l = new link n1 n2 in
  Printf.printf "'%s' -> '%s'\n" l#previous#name l#next#name
+8
source

All Articles