Programming thread

  • Want to keep track of this thread?
    Accounts can bookmark posts, watch threads for updates, and jump back to where you stopped reading.
    Create account
You ever accidentally get a correct answer?
From Common Lisp: A Gentle Introduction to Symbolic Computation:
Write MY-UNION a recursive version of UNION
Code:
(defun my-union (x y)
    (cond ((null x) y)
          ((not (member (car x) y))
              (cons (car x) (my-union (cdr x) y)))
          (t
              (my-union (cdr x) y))))

Code:
(defun my-union (x y)
    (append (x (my-recursive-union x y)))
    
(defun my-recursive-union (x y)
    (cond ((null y) nil)
          ((member (car y) x)
              (my-recursive-union x (cdr y)))
          (t
              (cons (car y) (my-recursive-union x (cdr y))))))

Tests:
Union
Code:
(union '(a b c d e) '(a c d c f)) --> (e b a c d c f)

First my-union
Code:
(my-union '(a b c d e) '(a c d c f)) --> (b e a c d c f)

Correct my-union
Code:
(my-union '(a b c d e) '(a c d c f)) --> (a b c d e f)
;;I think this one removes duplicates in the union list
;;compared to union

I am amazed I got an answer that is sort of the reverse of the solution in the book. Feels good!
 
Back
Top Bottom