Lisp:对列表中的所有值进行平方

Lisp: Squaring all values in a list

请耐心等待,因为我对 lisp 还是很陌生。我的函数(在本例中称为测试)的目标是计算列表中所有值的平方和 return 一个新列表。

例如,原始列表(1 2 3)。 新列表应该是 (1 4 9)

这是目前我所拥有的,

(defun test (n)
  (cond ((null n) nil)
        (t (cons * (car n) (car n))
           (test (cdr n)))))

但是我一直收到错误消息,我不确定如何继续。 任何帮助将非常感激!

在您的代码中有两个问题:cond 的语法(其他语言的 else 等同于 T),以及缺少乘法运算符的事实。

这是一个工作版本:

(defun test (n)
  (cond ((null n) nil)
        (t (cons (* (car n) (car n))
                 (test (cdr n))))))

此外,注意cond最常用于多个条件,而if用于单个条件:

(defun test (n)
  (if (null n)
      nil
      (cons (* (car n) (car n))
            (test (cdr n)))))