OCaml:对象定义 &克隆 [英] OCaml: Object definition & cloning

查看:47
本文介绍了OCaml:对象定义 &克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class backup =
  object (self : 'mytype)
    val mutable copy = None
    method save = copy <- Some {< copy = None >}
    method restore = match copy with Some x -> x | None -> self
  end;;

在这段代码中,有几处我不太明白.

In this piece of code, there are several things I do not quite understand.

  1. (self: 'mytype) self表示递归类,但是'mytype的作用是什么?

  1. (self: 'mytype) self means recursive class, but what is the role of 'mytype?

某些 {} 获取副本仍然为 None 的备份副本,并将其分配给副本?

Some {} gets a backup copy where copy is still None, and assign it to copy?

谢谢!!

推荐答案

在 C++、Java 和 JavaScript 中,执行方法的当前对象始终命名为 this.在 Smalltalk 中,它被命名为 self.在 OCaml 中,你可以给它任何你喜欢的名字.object 后面括号中出现的任何名称都是当前对象的名称.在这个例子中,当前对象被命名为self.(我不知道你所说的递归类"是什么意思.)

In C++, Java, and JavaScript the current object, the one executing the method, is always named this. In Smalltalk it's named self. In OCaml you can give it any name you like. Whatever name appears in parentheses after object is the name of the current object. In this example, the current object is named self. (I don't know what you mean by "recursive class.")

在某些情况下,为当前对象的类型命名是很有用的.同样,您可以通过在当前对象的名称之后放置 : 'name 来为其指定任何您喜欢的名称.在这个例子中,当前对象的类型被命名为'mytype.该名称未在代码中的任何地方使用,但如果代码变得更复杂,则可能会使用该名称.请注意,'mytype 不仅仅是类类型 backup 的另一个名称.在一个继承自backup的类中,'mytype代表这个继承类的类型.

In some cases it's useful to have a name for the type of the current object. Again, you can give it any name you like by putting : 'name after the name of the current object. In this example, the type of the current object is named 'mytype. The name isn't used anywhere in the code, but it might be used if the code were to get more complicated. Note that 'mytype is not just another name for the class type backup. In a class that inherits from backup, 'mytype represents the type of this inheriting class.

您对 save 方法的描述似乎是正确的.它创建当前对象的副本并将副本保存在名为 copy 的字段中.副本的copy 字段设置为None.即,即使包含对象已经有一个,副本也没有自己保存的副本.此方法使用特殊符号 {<... >},创建当前对象的副本.

Your description of the save method seems right. It creates a copy of the current object and saves the copy in the field named copy. The copy's copy field is set to None. I.e., the copy doesn't have its own saved copy even if the containing object already had one. This method uses the special notation {< ... >}, which creates a copy of the current object.

这篇关于OCaml:对象定义 &amp;克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆