我已经按照 SICP 2.5.3 中描述的思路编写了一个多项式类(除了使用 defclass)。我希望能够无缝地对多项式和常规数字进行加法和乘法,但我无法使更改类接受数字。
我试图通过将类从整数更改为 float 来简化问题:
(change-class 4 'float)
但这给了我错误:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION CHANGE-CLASS (7)>
when called with arguments
(4 #<BUILT-IN-CLASS FLOAT>).
[Condition of type SIMPLE-ERROR]
我从(仅供引用)收到了相同形式的错误:
(change-class 4 'polynomial)
我将继续实现手动转换,但我更喜欢使用内置的 clos 设施。
正如 Xach 指出的,我可以使用强制或 float 将 4 更改为 float 。这是我试图做的一个更简单的例子,并消除我的 update-instance-for- different-class 错误的任何可能性。
这是我尝试过但不起作用的较长版本:
(defclass polynomial ()
((var :accessor var :initarg :var :initform 'x)
(terms :accessor terms :initarg :terms :initform (make-empty-term-list))))
(defmethod update-instance-for-different-class :before ((old number)
(new polynomial)
&key)
(setf (slot-value new 'terms) (adjoin-term (make-term old 0)
(make-empty-term-list))))
(change-class 4 'polynomial)
我仍然收到类似上面示例的错误:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION CHANGE-CLASS (7)>
when called with arguments
(4 #<STANDARD-CLASS POLYNOMIAL>).
[Condition of type SIMPLE-ERROR]
最佳答案
您可以使用 COERCE 或 FLOAT 来执行此操作:
(float 4) => 4.0
(coerce 4 'float) => 4.0
关于common-lisp - 使用change-class从数字创建多项式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2532998/