Sorting 排序多项式公共Lisp
我正在尝试对以下格式编写的多项式列表进行排序: M[系数][总程度][变量列表] 例如: M 1 1 V 1 A M 1 2 V 1 A V 1 C M 1 2 V 2 A M 1 2 V 1 A V 1 B 这是:a+a*c+a^2+a*b,我需要得到a+a*b+c+a*a^2,因为a*b 我尝试使用函数sort,但我的输出是:Sorting 排序多项式公共Lisp,sorting,lisp,common-lisp,polynomials,Sorting,Lisp,Common Lisp,Polynomials,我正在尝试对以下格式编写的多项式列表进行排序: M[系数][总程度][变量列表] 例如: M 1 1 V 1 A M 1 2 V 1 A V 1 C M 1 2 V 2 A M 1 2 V 1 A V 1 B 这是:a+a*c+a^2+a*b,我需要得到a+a*b+c+a*a^2,因为a*b
((M 1 1 ((V 1 A))) (M 1 2 ((V 2 A))) (M 1 2 ((V 1 A) (V 1 B))) (M 1 2 ((V 1 A) (V 1 C))))
那就是a+a^2+a*b+a*c
我使用:
(defun sort-poly (a b)
(cond
(t (sort-poly-helper (varpowers a) (varpowers b)))))
(defun sort-poly-helper (a b)
(cond
((null a) (not (null b)))
((null b) nil)
((equal (third(first a)) (third(first b))) (sort-poly-helper (rest a) (rest b)))
(t (sort (list (third(first a)) (third(first b))) #'string-lessp))))
与:
要帮忙吗?
谢谢你对你想做什么的定义非常模糊,很难给出答案。但是开始的方法是停止编程,就像1956年一样,使用一些抽象 首先,让我们定义如何生成变量并获取其位:
(defun make-variable (name &optional (degree 1))
`(v ,name ,degree))
(defun variable-name (v)
(second v))
(defun variable-degree (v)
(third v))
现在让我们定义如何从变量列表中生成多项式。注意,多项式的总阶数是可以从所有变量的阶数计算出来的,所以我们这样做
(defun make-polynomial (variables &optional (coefficient 1))
;; The total degree of the polynomial can just be computed from the
;; degrees of its variables
`(m ,coefficient ,(reduce #'* variables :key #'variable-degree)
,variables))
(defun polynomial-coefficient (p)
(second p))
(defun polynomical-total-degree (p)
(third p))
(defun polynomial-variables (p)
(fourth p))
现在,给定多项式列表,我们可以使用我们构建的抽象对它们进行排序:我们不需要到处使用列表访问器,事实上,我们可以更改多项式或变量的表示形式,而什么都不知道
我猜你想要排序的是多项式中变量的最高阶,虽然它不是很清楚,而不是多项式的总阶,这会更容易。那么,让我们编写一个函数来提取最高的变量度:
(defun highest-variable-degree (p)
(reduce #'max (mapcar #'variable-degree (polynomial-variables p))))
现在我们可以对多项式列表进行排序
CL-USER 23 > (sort (list (make-polynomial (list (make-variable 'a)
(make-variable 'b 2)))
(make-polynomial (list (make-variable 'c)
(make-variable 'd))))
#'<
:key #'highest-variable-degree)
((m 1 1 ((v c 1) (v d 1))) (m 1 2 ((v a 1) (v b 2))))
请记住:现在已经不是1956年了。我已经提交了对您的代码块的编辑。常见的Lisp风格是不在自己的行中留下尾随括号。另外,在重新格式化的过程中,我注意到了一些可疑的事情,比如一个cond,在sort poly中只有一个t子句,而一个cond子句虽然有效,但却非常奇怪,永远不会做任何事情。谢谢。你说得对,他们只是经验不足的错误。我是lisp的初学者。这是真的,我解释得很糟糕。首先,我必须按单个单项式的总阶数排序。A*B总度数=2之后,我必须为单个单项式的字符排序一个多项式,并且等级相等,我必须将字符序列最小的一个放在第一位。我希望我表达得很好,解释得很清楚。谢谢你的回答。
CL-USER 23 > (sort (list (make-polynomial (list (make-variable 'a)
(make-variable 'b 2)))
(make-polynomial (list (make-variable 'c)
(make-variable 'd))))
#'<
:key #'highest-variable-degree)
((m 1 1 ((v c 1) (v d 1))) (m 1 2 ((v a 1) (v b 2))))