2012-04-11 83 views
5

我想弄清楚如何我可以用其他對象參數化OCaml對象。具體來說,我希望能夠創建一個link對象,它包含着node對象和向後node對象,我希望能夠通過說一些像創建一個鏈接:在OCaml中的對象內的對象

let link1 = new link node_behind node_ahead;; 

回答

8

對象是在正常的表達OCaml,因此您可以將它們作爲函數和類構造函數參數傳遞。有關更深入的解釋,請查看OCaml手冊中的related section

因此,舉例來說,你可以寫:

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