core=> (defrecord Puffball [id name])
core.Puffball
core=> (Puffball. 149 "Urist")
#core.Puffball{:id 149, :name "Urist"}
core=> (apply Puffball. [149 "Urist"])
CompilerException java.lang.RuntimeException: java.lang.ClassNotFoundException: Puffball., compiling:(NO_SOURCE_PATH:3)
core=> (apply Puffball [149 "Urist"])
ClassCastException java.lang.Class cannot be cast to clojure.lang.IFn clojure.core/apply (core.clj:600)
如何从矢量创建马勃菌?
答案 0 :(得分:8)
在Clojure 1.3中,记录定义自动引入工厂功能:
Clojure 1.3.0
user=> (defrecord Puffball [id name])
user.Puffball
user=> (apply ->Puffball [149 "Urist"])
#user.Puffball{:id 149, :name "Urist"}
->Puffball
是“位置”工厂功能;还有map->Puffball
就像它的名字所暗示的那样。
答案 1 :(得分:0)
对于那些不在1.3.x上的人(或需要记录以外的功能),下面用java方法和构造函数模拟apply
:
(defmacro applyj ([mc args] `(~mc ~@args)) ([mc x args] `(~mc ~x ~@args)) ([mc x y args] `(~mc ~x ~y ~@args)) ([mc x y z args] `(~mc ~x ~y ~z ~@args)))
user=> (defrecord Puffball [id name]) user.Puffball user=> (applyj Puffball. [149 "Urist"]) #:user.Puffball{:id 149, :name "Urist"}