OCaml: Object definition & cloning

好久不见. 提交于 2019-12-11 23:29:46

问题


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 means recursive class, but what is the role of 'mytype?

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

Thank you!!


回答1:


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.")

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.

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.



来源:https://stackoverflow.com/questions/19327654/ocaml-object-definition-cloning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!