在 Lisp 中组合 2 个列表
Combining 2 lists in Lisp
从 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表达式吗?
您不需要嵌套循环,只需要一个同时遍历 list
和 list2
的循环。嵌套循环会产生叉积,而不仅仅是组合相应的元素。
您得到的错误是因为您在 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))
从 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表达式吗?
您不需要嵌套循环,只需要一个同时遍历 list
和 list2
的循环。嵌套循环会产生叉积,而不仅仅是组合相应的元素。
您得到的错误是因为您在 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))