在 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 的进程命令?
I am attempting to learn OCaml by using compiled code instead of the top-level; however, much of the sample code online seems to appeal to the latter.
I would like to create a new Foo within a method of an object per below. This code does not compile, citing a syntax error with the doFooProc definition.
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;;
Additionally, the "let" syntax don't seem to be friendly within class definitions. Why is that?
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;;
How do I go about creating a new object of class foo in the doFooProc method and call the instantiated foo's process command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您基本上是正确的,但要么将语法与模块系统混淆,要么考虑其他语言。 接受我的考虑,你应该会好起来的!
小写“foo”表示对象,模块大写。 另外,您必须将 foo 的定义放在调用它的对象之上。 如果发生这种情况,您应该得到一个
Unbound class foo
。因为您没有匹配的
in
,而是有一个分号。 然后它就会起作用。 另外,您可以删除那些多余的括号,但这并不重要。是的。 这就像编写相互递归的函数和模块一样,用
and
关键字将它们连接起来。You're mostly correct, but are either confusing syntax with the module system, or thinking of other languages. Take my considerations and you should be good!
Lowercase "foo" for objects, modules are uppercase. Also, you must put the definition of foo above the object that calls it. You should get an
Unbound class foo
if this happens.Because you don't have a matching
in
, instead you have a semi-colon. Then it will work. Also, you can remove those extra parens, but it doesn't matter.Yes. It's just like writing mutually recursive functions and modules, you connect them with the
and
keyword.对于两个相互递归的类,使用 and 关键字
For two mutually recursive class, use the and keyword