Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects within objects in OCaml

Tags:

object

oop

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;;
like image 225
user1181523 Avatar asked Apr 11 '12 19:04

user1181523


1 Answers

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
like image 184
Thomas Avatar answered Oct 22 '22 15:10

Thomas