什么类型的功能?

Bel*_*lun 18 types clojure

让我们尝试一些对"类型"函数的调用:

user=> (type 10)
java.lang.Integer

user=> (type 10.0)
java.lang.Double

user=> (type :keyword?)
clojure.lang.Keyword
Run Code Online (Sandbox Code Playgroud)

现在有一个匿名函数:

user=> (type #(str "wonder" "what" "this" "is"))
user$eval7$fn__8
Run Code Online (Sandbox Code Playgroud)

A)这意味着"user $ eval7 $ fn__8"是什么意思? B)什么类型的功能?

"类型"的来源是:

user=> (source type)
(defn type
  "Returns the :type metadata of x, or its Class if none"
  {:added "1.0"}
  [x]
  (or (:type (meta x)) (class x)))
nil
Run Code Online (Sandbox Code Playgroud)

所以函数需要具有元数据的特定部分或者是类

检查匿名函数的元产生nada:

user=> (meta #(str "wonder" "what" "this" "is"))
nil
Run Code Online (Sandbox Code Playgroud)

尝试不同的方法:

user=> (defn woot [] (str "wonder" "what" "this" "is"))
#'user/woot
user=> (meta woot)
{:ns #<Namespace user>, :name woot}
Run Code Online (Sandbox Code Playgroud)

C)似乎有一些元,但我认为这是符号"woot"的元,对吧?

那个"或"的后半部分怎么样:

user=> (class #(str "wonder" "what" "this" "is"))
user$eval31$fn__32

user=> (class woot)
user$woot
Run Code Online (Sandbox Code Playgroud)

这些是什么:"用户$ eval31 $ fn__32"和"用户$ woot"以及它们来自哪里?

检查"类"函数产生:

user=> (source class)
(defn ^Class class
  "Returns the Class of x"
  {:added "1.0"}
  [^Object x] (if (nil? x) x (. x (getClass))))
nil
Run Code Online (Sandbox Code Playgroud)

并进一步调查收益率:

user=> (.getClass #(str "wonder" "what" "this" "is"))
user$eval38$fn__39

user=> (.getClass woot)
user$woot
Run Code Online (Sandbox Code Playgroud)

我不懂. D)这是一个哈希码:eval38 $ fn__39? E)这是一个符号:woot?

F)为什么函数没有类型?它不应该是一个IFn或什么?

Stu*_*rra 19

函数是类型clojure.lang.IFn,它是Java接口.

每个Clojure函数都被编译成一个实现的Java类clojure.lang.IFn.该名称user$eval7$fn__8是该类的"二进制类名称",即其在JVM中的内部名称.

  • 因为当类a实现类b时,它的类型仍然不是b. (4认同)

lev*_*and 15

Clojure构建于JVM之上.

JVM不支持开箱即用的第一类函数或lambdas.每个Clojure函数一旦编译,就会从JVM的角度成为它自己的匿名类.从技术上讲,每个功能都是它自己的类型.

它成为实现 IFn 的类,但是当你检索它的类型时,它会为你提供每次都不同的匿名类的名称.


mik*_*era 5

这是API 文档中的描述

Returns the :type metadata of x, or its Class if none
Run Code Online (Sandbox Code Playgroud)

您所看到的 ("user$eval7$fn__8") 是 Clojure 创建的内部生成内部类的名称,用于实现您定义的匿名函数。

您可能已经注意到,Clojure 不遵循标准的 Java 类命名约定:-)

请注意,该类实现了接口 clojure.lang.IFn - 这适用于所有 Clojure 函数。