当前位置 : 主页 > 大数据 > 区块链 >

arrays – 将Clojure协议扩展为原始数组

来源:互联网 收集:自由互联 发布时间:2021-06-22
我想扩展一个Clojure协议来处理 Java原始数组. (defprotocol PVectorisable (to-vector [a]))(extend-protocol PVectorisable ?????? (to-vector [coll] (Vectorz/create ^doubles coll)) java.util.List ... other implementations......) 这是
我想扩展一个Clojure协议来处理 Java原始数组.

(defprotocol PVectorisable
  (to-vector [a]))

(extend-protocol PVectorisable
  ??????
    (to-vector [coll]
      (Vectorz/create ^doubles coll))
  java.util.List
    ... other implementations......)

这是可能的,如果是这样,上面的扩展协议定义需要进行什么(代替“??????”)?

最简单的解决方案可能是用反射以编程方式抓取类.

(defprotocol do-a-thing
 (print-thing [thing]))

(extend-protocol do-a-thing
 (class (float-array 0))
  (print-thing [_]
   (println "it's a float array")))

Java的数组有些奇怪的名字.例如,浮点数组是[F.如果你试图直接在REPL中使用它,它会阻塞无法匹配的[.但是,您仍然可以使用此名称,例如Class / forName.

(defprotocol do-another-thing
 (print-another-thing [thing]))

(extend-protocol do-another-thing
 (Class/forName "[F")
  (print-another-thing [_]
   (println "it's still a float array")))

This article详细介绍了数组类.

网友评论