gpt4 book ai didi

list - 在 Lisp 中不使用 mapcar 将列表中的数字相乘(坐标方式)

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:56 25 4
gpt4 key购买 nike

我的代码输出有问题,我想是在我检查列表是否为 null 的条件时。

我试图完成的问题是:编写一个函数 vecmul,它将两个简单的数字列表作为输入。 vecmul 应该按坐标乘以这些列表,就像乘以向量一样。假设两个列表的长度相同。 [例如,(vecmul '(2 3 4 5) '(1 4 5 2)) 返回 (2*1 3*4 4*5 5*2)(2 12 20 10)。您不能使用 mapcar 来实现此功能]

到目前为止我有

(defun vecmul (list list2)
(cond ((null list) 0)
(t (cons (* (car list) (car list2))
(vecmul (cdr list) (cdr list2))))))

[170]> (setq l '(2 4 6))
(2 4 6)
[171]> (setq r '(1 3 5))
(1 3 5)
[172]> (vecmul l r)
(2 12 30 . 0)

我得到的数字是正确的,只是列表中添加了“.”。和列表末尾的“0”。我很确定这是因为我没有正确停止递归或没有正确使用 cond。我只是不确定如何更正它。

最佳答案

你几乎是对的。但是,当正确的终止是 nil 时,您将以 0 终止您的列表。此代码有效:

(defun vecmul (list list2)
(cond ((null list) nil)
(t (cons (* (car list) (car list2)) (vecmul (cdr list) (cdr list2))))))

当你调用 (cons 1 2) 时,你得到的 cons 单元被写为 (1 . 2)。符号 (1 2 3 4 5) 只是 (1 . (2 . (3 . (4 . (5 . nil))))) 的简写。如果最后一个 cons 单元格的 cdr6,而不是 nil,那么你会得到 (1 . (2 . (3 . (4 . (5 . 6))))),缩写为 (1 2 3 4 5 . 6)

关于list - 在 Lisp 中不使用 mapcar 将列表中的数字相乘(坐标方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15755477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com