my-union (Touretzky / exercise 8.52.)
Posted: Tue May 12, 2015 12:17 pm
Not really homework, but because of the kind of question I guess this is probably the right place:
I am going through Common Lisp: A Gentle Introduction to Symbolic Computation. In exercise 8.52., I do not understand why the solution in the book uses a helper function.
The book's solution:
My solution:
Mine seems to behave correctly. Does the book's solution have any advantages?
I found Lisp function: union while looking for an explanation and saw that my solution could not deal with non-list inputs, but the one from the book cannot either, and the Hyperspec says that the arguments of union should be proper lists.
I am going through Common Lisp: A Gentle Introduction to Symbolic Computation. In exercise 8.52., I do not understand why the solution in the book uses a helper function.
The book's solution:
Code: Select all
(defun my-union (x y)
(append x (union-recursively x y)))
(defun union-recursively (x y)
(cond ((null y) nil)
((member (first y) x)
(union-recursively x (rest y)))
(t (cons (first y)
(union-recursively
x
(rest y))))))
Code: Select all
(defun my-union (x y)
(cond ((null x) y)
((member (car x) y)
(my-union (cdr x) y))
(t (cons (car x)
(my-union (cdr x) y)))))
I found Lisp function: union while looking for an explanation and saw that my solution could not deal with non-list inputs, but the one from the book cannot either, and the Hyperspec says that the arguments of union should be proper lists.