我尝试实现表示算术表达式的接口。该接口将由 java 端使用,但整个逻辑都在 clojure 上。
有:
(defprotocol ExtendsExpression
(toTree [this]))
(extend-type String
ExtendsExpression
(toTree [this] (symbol this)))
(extend-type Number
ExtendsExpression
(toTree [this] this))
(definterface Expression
(toTree []))
(defrecord Expression1 [^String oper arg]
Expression
(toTree [this]
(list (symbol oper) (toTree arg))))
(defrecord Expression2 [^String oper arg1 arg2]
Expression
(toTree [this]
(list (symbol oper) (toTree arg1) (toTree arg2))))
(defrecord Expression3 [^String oper arg1 arg2 arg3]
Expression
(toTree [this]
(list (symbol oper) (toTree arg1) (toTree arg2) (toTree arg3))))
我尝试将其用作:
(toTree (Expression3. "+" "a" "b" (Expression2. "*" "c" "d")))
但我得到:
IllegalArgumentException No implementation of method: :toTree of protocol: #'user/ExtendsExpression found for class: user.Expression3 clojure.core/-cache-protocol-fn (core_deftype.clj:541)
为什么 clojure 尝试为 Expression3 调用 ExtendsExpression 的 toTree?我希望对于 Expression3 它将调用 Expression 接口的 toTree 方法。