【问题标题】:Lisp Product FunctionLisp 产品功能
【发布时间】:2018-09-02 02:43:21
【问题描述】:

我刚开始学习 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 

我不知道从这里去哪里。

【问题讨论】:

    标签: function common-lisp multiplication


    【解决方案1】:

    cond 表达式的第一个子句如下:

    如果 x 是一个 cons 单元格,则将其第一个元素(假定为数字)乘以对其第二个元素(或 NIL)调用 product 的结果。

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

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

    【讨论】:

    • 谢谢,这有帮助。我会尝试添加您建议的更改。
    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多