2009-02-04 76 views
4

我試圖通過使用編譯代碼而不是頂層來學習OCaml;然而,網上的大部分示例代碼似乎都吸引了後者。在OCaml中即時創建對象

我想創建一個新的Foo內每個對象的方法下面。此代碼不會編譯,引用doFooProc定義的語法錯誤。

class bar = 
object (self) 
method doFooProc = (new Foo "test")#process 
end;; 

class foo (param1:string)= 
object (self) 
method process = Printf.printf "%s\n" "Processing!" 
initializer Printf.printf "Initializing with param = %s\n" param1 
end;; 

此外,「let」語法在類定義中似乎不友好。這是爲什麼?

class bar = 
object (self) 
method doFooProc = 
    let xxx = (new Foo "test"); 
    xxx#process 
end;; 

class foo (param1:string)= 
object (self) 
method process = Printf.printf "%s\n" "Processing!" 
initializer Printf.printf "Initializing with param = %s\n" param1 
end;; 

我如何去在doFooProc方法創建類Foo的一個新對象,並調用實例化Foo的進程的命令?

回答

2

大部分情況都是正確的,但是要麼與模塊系統混淆語法,要麼考慮其他語言。考慮我的考慮,你應該很好!

我想每下面 的物體的方法中創建一個新的Foo 。此代碼無法編譯, 引用了doFooProc定義的語法錯誤和 定義。

對於小寫字母「foo」,模塊是大寫的。另外,您必須將foo的定義放在調用它的對象的上方。如果發生這種情況,你應該得到一個Unbound class foo

class bar = 
object (self) 
method doFooProc = (new foo "test")#process 
end;; 

此外,「讓」的語法似乎並沒有成爲類定義中友好。這是爲什麼?

因爲您沒有匹配in,而是您有一個分號。然後它會工作。此外,你可以刪除那些額外的parens,但沒關係。

class bar = 
object (self) 
method doFooProc = 
    let xxx = (new Foo "test") in 
    xxx#process 
end;; 

如果說,在FOO的方法實例化 酒吧爲好,有沒有什麼辦法來逃避 與 訂購內 源文件中的類定義產生的問題?

是。這就像編寫相互遞歸的函數和模塊一樣,你可以用and關鍵字連接它們。

class bar = 
    object (self) 
    method doFooProc = (new foo "test")#process 
    end 

and foo (param1:string) = 
    object (self) 
    method process = Printf.printf "%s\n" "Processing!" 
    initializer Printf.printf "Initializing with param = %s\n" param1 
    end 
+0

你說得對。我養成了對其他語言的類名使用大寫字母的習慣,並繼續使用OCaml進行恢復。謝謝! – 2009-02-04 18:43:01

+0

呃。只是要清楚。你可以在引用模塊和其他文件時採取這種直覺(因爲它們是隱式模塊) – nlucaroni 2009-02-04 18:44:53

2

兩個相互遞歸類,使用和關鍵字

class bar = 
    object (self) 
    method doFooProc = 
     let xxx = (new foo "test") in 
     xxx#process 
    end 
and foo (param1:string)= 
    object (self) 
    method process = Printf.printf "%s\n" "Processing!" 
    initializer Printf.printf "Initializing with param = %s\n" param1 
    method bar = new bar 
    end;;`