user1181523
user1181523

Reputation: 71

Objects within objects in OCaml

I'm trying to figure out how I can parameterize OCaml objects with other objects. Specifically I want to be able to create a link object which contains a forward node object and a backwards node object, and I want to be able to create a link by saying something like:

let link1 = new link node_behind node_ahead;;

Upvotes: 5

Views: 138

Answers (1)

Thomas
Thomas

Reputation: 5048

Objects are normal expressions in OCaml, so you can pass them as function and class constructor arguments. For a deeper explanation, look at the related section in OCaml manual.

So for instance, 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

Upvotes: 8

Related Questions