我不介意承认这是一项令我难过的家庭作业.任何向正确方向的推动都是有用的.
我需要编写一个返回两个给定列表的并集的函数.我相信我的逻辑是合理的,但是Lisp语法正在推动我的发展.
到目前为止我的解决方案是这样
(defun inList (e L)
(cond
((null L)
nil)
((equal (first L) e)
T)
(T
(inList e (rest L)))))
(defun union2 (L1 L2)
(cond
((null L2)
L1)
((not (inList (first L2) L1))
(append (union2 L1 (rest L2)) (first L2)))
(T
(union2 L1 (rest L2)))))
Run Code Online (Sandbox Code Playgroud)
当我使用空列表作为第二个参数测试函数,或者第二个参数是一个列表,其中每个项目都是第一个列表的成员时,它可以正常工作.
但是,当(union2 '(1 2 3) '(4 5 6))
我接受测试时
6 is not of type list
.
我很确定我的错误是: (append (union2 L1 (rest L2)) (first L2)
至于那时,(first L2)
显然不是一个清单.然而,写它((first L2))
是给我的Badly formed lambda
.
正如我所说,任何提示或指示将不胜感激.
你真的需要缩进你的代码.大多数Lisp用户都理解以下内容.它是自动且正确缩进的,并且在它们自己的行上没有括号.
(defun union2 (L1 L2)
(cond
((null L2) L1)
((not (inList (first L2) L1))
(append (union2 L1 (rest L2))
(first L2)))
(T (union2 L1 (rest L2)))))
Run Code Online (Sandbox Code Playgroud)
所以你认为,这(append ... (first L2))
是一个问题吗?
append
期望列表作为参数.第一个元素l2
可能不是列表.
你如何列出名单?
(append l1 l2 ...)
返回附加列表的列表(cons item l1)
返回一个item
添加到前面的列表l1
.(list e1 ...)
返回包含项目的列表e1
...作为元素.它需要零个或多个参数.上述之一应该可以帮助您从项目创建新列表.
另请注意,附加到列表末尾不是Lisp中的有效列表操作.首选将元素添加到列表的前面.
归档时间: |
|
查看次数: |
2927 次 |
最近记录: |