gpt4 book ai didi

lisp - 在 Lisp 中组合 2 个列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:19 24 4
gpt4 key购买 nike

从 2 个简单列表(例如 (1 2 3) 和 (a b c))我试图创建一个列表列表 ((1 a) (2 b) (3 c))。但是,以下代码不起作用:

(defun comblist_op (list1 list2)
(let ((combl '()))
(loop for i in list1 do(
loop for j in list2 do(
(push (list i j) combl))))
combl))

错误是:

*** - SYSTEM::%EXPAND-FORM: (PUSH (LIST I J) COMBL) should be a lambda expression

这里需要写lambda表达式吗?

最佳答案

您不需要嵌套循环,只需要一个同时遍历 listlist2 的循环。嵌套循环会产生叉积,而不仅仅是组合相应的元素。

您得到的错误是因为您在 do 之后的表达式周围放置了一组额外的括号。它不需要您将它们包装起来。

(defun comblist (list1 list2) 
(let ((combl '()))
(loop for i in list1
for j in list2
do (push (list i j) combl))
(nreverse combl)))

您需要反转结果列表,因为 PUSH 将以与原始列表相反的顺序创建它。

您还可以使用LOOP 的内置COLLECT 运算符。

(defun comblist (list1 list2) 
(loop for i in list1
for j in list2
collect (list i j)))

如果您想要两个列表中元素的所有组合,嵌套循环将起作用。只需在 DO 表达式周围添加额外的括号即可解决问题。

(defun comblist (list1 list2) 
(let ((combl '()))
(loop for i in list1
do
(loop for j in list2
do
(push (list i j) combl)))
combl))

关于lisp - 在 Lisp 中组合 2 个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277936/

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