list - 将每个子列表的第一个元素乘以 -1?口齿不清

标签 list lisp common-lisp

作为一个更大项目的一部分,我希望能够将每个子列表的每个第一个元素乘以 -1。我正在尝试像这样使用递归来做到这一点:

(defun negative (secondpoly)
    (let ((t1(car secondpoly))
         (rem(cdr secondpoly)))
        (let ((c1(car t1)))
            (if (not (null (cdr secondpoly)))
                (negative (append (* c1 -1) rem))
            )
        )
    )
)

有了这个输入:

(pminus '((5 x 2)(100 x 2)))

我想收到这个输出:

(pminus '((-5 x 2)(-100 x 2)))

我想知道是否有人可以告诉我一个方法来做到这一点?

最佳答案

如果您的输入确实是这样的:'(pminus ((5 x 2)(100 x 2)))

(defun negative-first (poly)
  (cons (car poly)
        (mapcar (lambda (el)
                  (cons (- (car el)) (cdr el)))
                (cadr poly))))

CL-USER> (negative-first '(pminus ((5 x 2)(100 x 2))))
(PMINUS (-5 X 2) (-100 X 2))

但对我来说似乎解释有误,你的输入是 '((5 x 2)(100 x 2)) 如果是这样,你的函数是:

(defun negative-first (poly)
  (mapcar (lambda (el)
            (cons (- (car el)) (cdr el)))
          poly))


CL-USER> (negative-first '((5 x 2)(100 x 2)))
((-5 X 2) (-100 X 2))

如果您需要处理更多嵌套和复杂的数据,您可能应该了解一些示例,此函数将仅适用于一级 ((5 x 2) (100 x 2) (40 x 3) 。 ... )

关于list - 将每个子列表的第一个元素乘以 -1?口齿不清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400499/

相关文章:

python - Python 中的最内层列表

html - CSS:在绝对列表中每个 li 元素 +x 像素

python - 迭代同一个列表两次并避免在 python 中重复

functional-programming - 在一行中打印答案、 "should be"和所需的答案 [方案(初级学生语言)]

lisp - 使用 Lisp : define a function that takes a list and a number and returns true if the number occurs in the list

scope - 避免无意中使用照应宏的陷阱

java - 在 Java 中将 for-each 嵌套在同一个列表中?

emacs - Lisp:既未声明也未绑定(bind) CHAR

algorithm - 为什么 Josef Stein 的二进制 GCD 算法的这种实现仅适用于某些情况?

common-lisp - 关键字命名空间污染