I don't mind admitting that this is a homework task that has me stumped. Any push in the right direction would be useful.
I'm required to write a function that returns the union of the two given lists. I believe my logic is sound, but Lisp syntax is driving me up a wall.
My solution so far is this.
(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)))))
When I test the function with an empty list as the second argument, or with the second argument being a list in which every item is a member of the first list, it works correctly.
However, when tested with
(union2 '(1 2 3) '(4 5 6))
I get 6 is not of type list
.
I'm fairly certain that my error is in: (append (union2 L1 (rest L2)) (first L2)
As at that point, (first L2)
is obviously not a list. However, writing it as ((first L2))
is giving me Badly formed lambda
.
As I said, any tips or pointers would be appreciated.
You really need to indent your code. The following is understood by most Lisp users. It is automatically and properly indented and has no parentheses on their own lines.
(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)))))
So you think, (append ... (first L2))
is a problem?
append
expects lists as arguments. The first element of l2
probably is not a list.
How do you make a list?
(append l1 l2 ...)
returns a list of the appended lists(cons item l1)
returns a list with the item
added to the front of l1
.(list e1 ...)
returns a list with the items e1
... as elements. It takes zero or more arguments.One of the above should help you to create a new list from an item.
Also note that appending to the end of a list is not an efficient list operation in Lisp. Adding elements to the front of a list is preferred.