gpt4 book ai didi

common-lisp - 使用 change-class 从一个数字创建一个多项式对象

转载 作者:行者123 更新时间:2023-12-04 06:56:10 26 4
gpt4 key购买 nike

我已经按照 SICP 2.5.3 中描述的方式编写了一个多项式类(使用 defclass 除外)。我希望能够无缝地添加和乘以多项式和常规数字,但我不能让 change-class 接受一个数字。

我试图通过将类从整数更改为浮点数来简化问题:

(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]

我从 (fyi) 得到相同形式的错误:
(change-class 4 'polynomial)

我将继续实现手动转换,但我更愿意使用内置的 clos 设施。

正如 Xach 指出的那样,我可以使用强制或浮点数将 4 更改为浮点数。这旨在作为我试图做的事情的一个更简单的例子,并消除我的不同类更新实例错误的任何可能性。

这是我尝试过但不起作用的较长版本:
(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]

最佳答案

您不能对数字使用 CHANGE-CLASS。数字不是 CLOS 类的实例。 CHANGE-CLASS 也被认为是 破坏性地将实例修改为新类,而不更改原始实例的身份。

我要么:

  • 将方法添加到 CHANGE-CLASS 中,可以执行您想要的操作
  • 或编写一个函数 CHANGE,该函数实现各种自定义强制规则并调用 CHANGE-CLASS 以对从一个 CLOS 类到另一个 CLOS 类的任何更改进行调用。
  • 关于common-lisp - 使用 change-class 从一个数字创建一个多项式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2532998/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com