首先,我是 Clojure 的新手,所以这可能是个愚蠢的问题。
作为一个学习练习,我有一个简单的文本冒险多方法系统工作。我现在想从使用关键字更改为某种形式的“classiness”,它可以保存与“sack”、“sword”等各个实例有关的数据。
是defrecord
去这里的路吗?
问题:我可以使用 Clojure 的派生来创建我的 defrecord 类类型的层次结构吗?似乎与此类似,但接受的答案是“不,也许使用接口”。
答案真的没有吗?为了使用 Clojure 的多方法,我是否必须将所有数据表示形式编写为 Java 类?
谢谢,
克里斯。
工作代码:
(derive ::unlit_root ::room)
(derive ::room ::thing)
(derive ::item ::thing)
(derive ::sword ::item)
(derive ::container ::thing)
(derive ::sack ::container)
(derive ::sack ::item)
(derive ::wardrobe ::furniture)
(derive ::furniture ::thing)
(derive ::wardrobe ::furniture)
(defmulti put (fn [x y z] [x y z]))
(defmethod put [::room ::thing ::thing] [x y z] "you can only put items into containers")
(defmethod put [::room ::sword ::sack] [x y z] "the sword cuts the sack")
(defmethod put [::room ::item ::container] [x y z] "ordinary success")
(defmethod put [::unlit_room ::thing ::thing] [x y z] "it's too dark, you are eaten by a grue")
(defmethod put [::room ::sack ::wardrobe] [x y z] "you win")
(defmethod put [::room ::item ::sack] [x y z] "you put it in the sack")
(defmethod put [::room ::furniture ::thing] [x y z] "it's too big to move")
下面,是我迄今为止尝试过的,但我在第一次得到一个错误derive
:
ClassCastException java.lang.Class cannot be cast to clojure.lang.Named clojure.core/namespace (core.clj:1496)
.
(defrecord Item [name])
(defrecord Weapon [name, damage])
(defrecord Furniture [name])
(defrecord Container [name])
(defrecord Bag [name])
(derive Weapon Item)
(derive Container Item)
(derive Bag Container)
(derive Furniture Container)
(def sword (Weapon. "sword" 10))
(def apple (Item. "apple"))
(def cupboard (Furniture. "cupboard"))
(def bag (Bag. "bag"))
(defmulti putin (fn [src dst] [src dst]))
(defmethod putin [Item Container] [src dst] :success_0)