OCaml中对象内的对象

use*_*523 5 oop ocaml object

我试图找出如何用其他对象参数化OCaml对象.具体来说,我希望能够创建一个link包含前向node对象和后向node对象的对象,我希望能够通过以下方式创建链接:

let link1 = new link node_behind node_ahead;;
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 8

对象是OCaml中的普通表达式,因此您可以将它们作为函数和类构造函数参数传递.有关更深入的解释,请查看OCaml手册中的相关部分.

例如,您可以写:

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
Run Code Online (Sandbox Code Playgroud)