Lisp 产品功能

Lisp Product Function

我刚刚开始使用 lisp。我正在尝试制作一个用 Lisp 编写的产品功能。该函数应该接受一个任意参数 x,以及 returns 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 表达式的第一个子句如下所示:

If x is a cons cell, multiply its first element (assumed to be a number) with the result of calling product on its second element (or NIL).

(product '(x 5))(product '((2 2) 3)) 都失败了,因为第一个元素不是数字。您应该乘以 (product (car x)) 而不是 (car x),以便将您的任意项转换为数字。

另请注意,cadr 上的递归不足以遍历输入列表的所有元素。您可能打算使用 cdr.