为什么这种类型的注释失败了?

时间:2014-12-27 21:31:08

标签: clojure

我想了解为什么我无法在clojure中为此点积函数添加返回类型注释。

(defn dot3
  "3d vector dot product"
  ^double [^doubles [u0 u1 u2]
           ^doubles [v0 v1 v2]]
  (+ (* u0 v0) (* u1 v1) (* u2 v2)))

在下面的日志中,您可以看到减法的注释工作正常,如果我删除^double返回类型注释,它也可以。但是,上面的代码在调用时会产生错误:

user=> (dot3 [4 5 6] [1 2 3])    
ClassCastException user$dot3 cannot be cast to clojure.lang.IFn$OOD  user/eval3487 (form-init8441686871120943013.clj:1)

提前致谢,

- 罗杰

thunder 13:17:21 clojure> lein version
Leiningen 2.5.0 on Java 1.8.0_25 Java HotSpot(TM) 64-Bit Server VM
thunder 13:17:28 clojure> lein new test123
Generating a project called test123 based on the 'default' template.
The default template is intended for library projects, not applications.
To see other templates (app, plugin, etc), try `lein help new`.
thunder 13:18:09 clojure> cd test123
thunder 13:18:14 test123> lein repl
nREPL server started on port 57240 on host 127.0.0.1 - nrepl://127.0.0.1:57240
REPL-y 0.3.5, nREPL 0.2.6
Clojure 1.6.0
Java HotSpot(TM) 64-Bit Server VM 1.8.0_25-b17
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

user=> (defn vsub3
  #_=>   "3d vector subtraction"
  #_=>   ^doubles [^doubles [u0 u1 u2]
  #_=>             ^doubles [v0 v1 v2]]
  #_=>   [(- u0 v0) (- u1 v1) (- u2 v2)])
#'user/vsub3
user=> (vsub3 [4 5 6] [1 2 3])
[3 3 3]
user=> (defn dot3
  #_=>   "3d vector dot product"
  #_=>   ^double [^doubles [u0 u1 u2]
  #_=>            ^doubles [v0 v1 v2]]
  #_=>   (+ (* u0 v0) (* u1 v1) (* u2 v2)))
#'user/dot3
user=> (dot3 [4 5 6] [1 2 3])
ClassCastException user$dot3 cannot be cast to clojure.lang.IFn$OOD  user/eval3487 (form-init8441686871120943013.clj:1)
user=> (defn dot3
  #_=>   "3d vector dot product"
  #_=>   [^doubles [u0 u1 u2]
  #_=>    ^doubles [v0 v1 v2]]
  #_=>   (+ (* u0 v0) (* u1 v1) (* u2 v2)))
#'user/dot3
user=> (dot3 [4 5 6] [1 2 3])
32

1 个答案:

答案 0 :(得分:1)

您提供的类型注释与指定函数参数的方式不兼容。

解构阻止编译正确的代码。事实证明,这是当前Clojure版本中的一个错误,但将在1.7版本中修复。

以下版本正常运行:

(defn dot3
  "3d vector dot product"
  ^double [^doubles u
           ^doubles v]
   (+ (* (aget u 0) (aget v 0))
      (* (aget u 1) (aget v 1))
      (* (aget u 2) (aget v 2))))

user=> (dot3 (double-array [4.0 5.0 6.0]) (double-array [1.0 2.0 3.0]))
32.0