代码之家  ›  专栏  ›  技术社区  ›  Belun

什么类型的函数?

  •  18
  • Belun  · 技术社区  · 14 年前

    让我们尝试调用“type”函数:

    user=> (type 10)
    java.lang.Integer
    
    user=> (type 10.0)
    java.lang.Double
    
    user=> (type :keyword?)
    clojure.lang.Keyword
    

    现在有一个匿名函数:

    user=> (type #(str "wonder" "what" "this" "is"))
    user$eval7$fn__8
    

    (一) 这是什么意思“用户$eval7$fn\u8”? (二)

    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
    

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

    user=> (meta #(str "wonder" "what" "this" "is"))
    nil
    

    尝试不同的方法:

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

    (三)

    “或”的后半部分呢:

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

    这些是什么:“user$eval31$fn\uu32”和“user$woot”它们来自哪里?

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

    进一步调查产量:

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

    我不明白。 (D) 这是哈希码:eval38$fn\u39吗? 电子) 这是一个符号:woot?

    (F)

    4 回复  |  直到 14 年前
        1
  •  18
  •   levand    14 年前

    Clojure构建在JVM上。

    JVM不支持开箱即用的一级函数或lambda。从JVM的角度来看,每个Clojure函数一经编译,就成为自己的匿名类。从技术上讲,每个函数都是自己的类型。

    它变成的阶级 工具

        2
  •  21
  •   Stuart Sierra    14 年前

    clojure.lang.IFn

    每个Clojure函数都被编译成一个Java类,该类实现 user$eval7$fn__8 是该类的“二进制类名”,即它在JVM中的内部名称。

        3
  •  5
  •   mikera    14 年前

    API docs

    Returns the :type metadata of x, or its Class if none
    

    您看到的(“user$eval7$fn\u8”)是Clojure为实现您定义的匿名函数而创建的内部生成的内部类的名称。

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

        4
  •  2
  •   jneira    14 年前

    我是个新手,但我要大胆一点。首先,我们对函数的“类型”有两种不同的含义,一种是clojure内部的java接口和类,另一种是作为编程概念的函数类型。采用第二种方法,函数的类型将是其返回值的类型(或其参数类型和返回值类型):

    1) 我想所有函数都实现了 IFn 接口,不管它们当前的类是什么

    2) clojure自动生成的类名在函数是匿名的或命名的情况下会有所不同,但在这两种情况下似乎都是内部类(通常它们的名称用$分隔,从外部类到内部类)

    3) 如果在函数定义中对其进行注释,则返回值的类型可以在函数元数据的:tag键中。例如,您公开的函数类将class作为其返回类型,因为在其def中,名称前面有一个^class。

    我假设您熟悉java(或类似的oop语言),如果不熟悉的话,我很抱歉