为什么 Clojure 有 5 种方法来定义类而不是只有一种? [英] Why does Clojure have 5 ways to define a class instead of just one?

查看:19
本文介绍了为什么 Clojure 有 5 种方法来定义类而不是只有一种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 有 gen-class、reify、proxy 以及 deftype 和 defrecord 来定义新的类数据类型.对于一种重视语法简单并厌恶不必要的复杂性的语言来说,这似乎是一种失常.有人可以解释为什么会这样吗?Common Lisp 风格的 defclass 就够了吗?

Clojure has gen-class, reify, proxy and also deftype and defrecord to define new class-like datatypes. For a language that values syntactic simplicity and abhors unnecessary complexity, it seems like an aberration. Could someone explain why it is so? Could Common Lisp-style defclass have sufficed?

推荐答案

这是三个不同因素的混合:

This is a mix of three different factors:

  1. jvm 的特定类型系统
  2. 在定义类型时需要针对不同的用例使用略有不同的语义
  3. 事实上,随着语言的发展,其中一些开发得较早,而另一些开发得较晚.

首先,让我们考虑一下它们的作用.deftypegen-class 的相似之处在于它们都为提前编译定义了一个命名类.Gen-class 首先出现,其次是 clojure 1.2 中的 deftype.Deftype 是首选,具有更好的性能特征,但限制性更强.deftype 类可以符合一个接口,但不能从另一个类继承.

So first, let's consider what these do. deftype and gen-class are similar in that they both define a named class for ahead-of-time compilation. Gen-class came first, followed by deftype in clojure 1.2. Deftype is preferred, and has better performance characteristics, but is more restrictive. A deftype class can conform to an interface, but cannot inherit from another class.

Reifyproxy 都用于在运行时动态创建匿名类的实例.代理首先出现,在 clojure 1.2 中 reify 与 deftype 和 defrecord 一起出现.Reify 是首选,就像 deftype 一样,语义不是太严格.

Reify and proxy are both used to dynamically create an instance of an anonymous class at runtime. Proxy came first, reify came along with deftype and defrecord in clojure 1.2. Reify is preferred, just as deftype is, where the semantics are not too restrictive.

这就留下了为什么 deftype 和 defrecord 的问题,因为它们同时出现,并且具有相似的作用.对于大多数目的,我们会想要使用 defrecord:它具有我们所知道和喜爱的所有各种 clojure 优点、可排序性等等.Deftype 旨在用作实现其他数据结构的低级构建块.它不包括常规的 clojure 接口,但它确实有可变字段的选项(尽管这不是默认设置).

That leaves the question of why both deftype and defrecord, since they appeared at the same time, and have a similar role. For most purposes, we will want to use defrecord: it has all the various clojure goodness that we know and love, sequability and so forth. Deftype is intended for use as a low level building block for the implementation of other datastructures. It doesn't include the regular clojure interfaces, but it does have the option of mutable fields (though this isn't the default).

如需进一步阅读,请查看:

For further reading check out:

clojure.org 数据类型页面

引入 deftype 和 reify 的 google 群组帖子

这篇关于为什么 Clojure 有 5 种方法来定义类而不是只有一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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