5

我试图弄清楚如何使用其他对象参数化 OCaml 对象。具体来说,我希望能够创建一个link包含前向node对象和后向对象的node对象,并且我希望能够通过说以下内容来创建链接:

let link1 = new link node_behind node_ahead;;
4

1 回答 1

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
于 2012-04-11T19:40:44.153 回答