我刚刚开始使用lisp。我正在尝试用Lisp编写一个产品函数。该函数应该接受任意参数x,并返回x中包含的所有数值的乘积。它应该产生以下内容:
>(product 'x) -> 1
>(product '(x 5)) -> 5
>(product '((2 2)3)) -> 12
>(product '((a 3)(2 1))) -> 6
我能够做到以下几点:
(defun product (x)
"This function takes in an arbitrary parameter x, and returns the product of all numeric values contained within x."
(cond
((consp x) (* (car x)(product (cadr x))))
((numberp x) x)
(t 1)
)
)
这处理像这样的情况
(product '(2 5))-> 10
(product 'x) -> 1
但不适合像:
>(product '(x 5)) -> 5
>(product '((2 2)3)) -> 12
我不知道从哪里开始。
cond
表达式的第一个子句如下:
如果x是cons单元格,则将其第一个元素(假设为数字)与在其第二个元素(或NIL)上调用
product
的结果相乘。
(product '(x 5))
和(product '((2 2) 3))
都失败了,因为第一个元素不是数字。您应该乘以(product (car x))
而不是(car x)
,以便将您的任意项转换为数字。
另请注意,在cadr
上递归不足以迭代输入列表的所有元素。你可能打算使用cdr
。