4

我正在尝试通过使用编译代码而不是顶级代码来学习 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 的 process 命令?

4

2 回答 2

2

您大多是正确的,但要么将语法与模块系统混淆,要么考虑其他语言。以我的考虑,你应该很好!

我想在下面的对象的方法中创建一个新的 Foo 。此代码无法编译,引用 doFooProc 定义的语法错误。

对象的小写“foo”,模块是大写的。此外,您必须将 foo 的定义放在调用它的对象之上。如果发生这种情况,您应该得到一个Unbound class foo

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

此外,“let”语法在类定义中似乎并不友好。这是为什么?

因为你没有匹配in,而是你有一个分号。然后它将起作用。此外,您可以删除那些额外的括号,但这并不重要。

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

比如说,如果 foo 中的一个方法也实例化了一个 bar,那么有没有办法避免在源文件中对类定义进行排序时出现的问题?

是的。这就像编写相互递归的函数和模块一样,您将它们与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
于 2009-02-04T18:37:03.320 回答
2

对于两个相互递归的类,使用 and 关键字

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;;`
于 2009-02-04T19:34:00.787 回答