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

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

问题描述

Clojure具有gen-class,reify,proxy以及deftype和defrecord来定义新的类类数据类型。对于一种重视句法简单性和厌恶不必要的复杂性的语言,它似乎是一种错误。
有人可以解释为什么是这样吗?

解决方案

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


  1. jvm的特定类型系统

  2. 定义类型时,对于不同的用例需要略有不同的语义

  3. 首先,让我们考虑一下这些。 deftype gen-class 类似,因为它们都为提前编译定义了一个命名类。 Gen类先来了,其次是cloxure 1.2中的deftype。 Deftype是优选的,并且具有更好的性能特性,但是更具限制性。 deftype类可以符合接口,但不能从另一个类继承。



    Reify 代理用于在运行时动态创建一个匿名类的实例。代理来了第一,reify与deftype和defrecord在clojure 1.2。 Reify是首选,正如deftype是,其中语义不是太限制。



    这留下了为什么deftype和defrecord的问题,因为他们同时出现,并具有类似的作用。对于大多数目的,我们将使用defrecord:它具有我们所知道和爱的所有各种clojure善良,sequables等等。 Deftype旨在用作实现其他数据结构的低级构建块。它不包括常规clojure接口,但它有可变字段的选项(虽然这不是默认的)。



    进一步阅读签出:



    clojure.org数据类型页面



    引入deftype和reify的google组线程


    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. The particular type system of the jvm
    2. The need for slightly different semantics for different use cases when defining types
    3. The fact that some of these were developed earlier, and some later, as the language has evolved.

    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.

    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.

    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:

    The clojure.org datatypes page

    The google group thread where deftype and reify were introduced

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

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