【问题标题】:Apply function recursively across 2 lists in Common Lisp在 Common Lisp 中的 2 个列表中递归应用函数
【发布时间】:2014-12-11 15:36:59
【问题描述】:

我有一个用通用 LISP 编写的函数,它将 2 个多项式的第一项相乘,它完全按照我的意愿工作(使用我编写的其他函数):

(defun firsttermmultiply (p1 p2)
    (let ((t1p1(car p1))
          (t1p2(car p2))
          (rem1(cdr p1))
          (rem2(cdr p2)))
        (cons (coeff t1p1 t1p2) (cutfront t1p1 t1p2)) 
    )
)

p1 和 p2 是多项式,我想通过这两个列表进行递归,以便我有一个长列表,其中 p1 和 p2 中的所有项都已应用于该行:

(cons (coeff t1p1 t1p2) (cutfront t1p1 t1p2)) 

我知道它需要使用 rem1 和 rem2 作为单独递归行的参数,但我无法理解结构。

我必须在功能上这样做,所以我不能使用循环结构,只能使用递归。

【问题讨论】:

  • 你能展示一些示例输入和输出吗?现在还不清楚您要做什么。记住 mapcar 可以接受多个列表可能会有所帮助。例如,(mapcar '+ '(1 2) '(3 4)) => (4 6).
  • 我不认为显示的代码按预期工作。 p1p2 的尾部从未使用过,也不会出现在结果中。

标签: list function recursion lisp common-lisp


【解决方案1】:

是其中之一吗?假设这些多边形的顺序相同。

(defun firsttermmultiply (p1 p2)
  (if (or (null p1) (null p2))
      nil
      (let ((t1p1(car p1))
            (t1p2(car p2))
            (rem1(cdr p1))
            (rem2(cdr p2)))

        (cons (coeff t1p1 t1p2) (firsttermmultiply rem1 rem2)))))


(defun firsttermmultiply (p1 p2)
  (if (or (null p1) (null p2))
      nil
      (let ((t1p1(car p1))
            (t1p2(car p2))
            (rem1(cdr p1))
            (rem2(cdr p2)))

        (cons (cons (coeff t1p1 t1p2) (cutfront t1p1 t1p2))
              (firsttermmultiply rem1 rem2)))))


(defun firsttermmultiply (p1 p2)
  (if (or (null p1) (null p2))
      nil
      (let ((t1p1(car p1))
            (t1p2(car p2))
            (rem1(cdr p1))
            (rem2(cdr p2)))

        (cons (coeff t1p1 t1p2)
              (cons (cutfront t1p1 t1p2)
                    (firsttermmultiply rem1 rem2))))))

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 2018-05-16
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多