lotrsimp12345 37 Posting Pro in Training

Here's my code.

(define L ())
(define (union L1 L2)
  ;continue until one list is empty
  (do()
    ((or (null? L1) (null? L2)))
    (cond
      ((<(car L1)(car L2)) (attach(car L1)(cdr L1)L2))
      ((eq?(car L1)(car L2)) (attach(car L1)(cdr L1)(cdr L2)))
      (else(>(car L1)(car L2)) (attach(car L2)L1(cdr L2)))
    )
  )
;after which you continue to add add while one list isn't empty and ;the second one isn't empty. I know I need a new attach function. 
)

(define (attach item List1 List2)
  (cons item L)
  (union List1 List2)
)

Dani AI

Generated

Note for : the main problems in your snippet are using a global L as an accumulator, having attach call union (which causes runaway recursion), and relying on eq? for numeric equality. A simpler, safer approach is a single recursive merge that returns a new list. That avoids a separate attach and makes control flow obvious.

Example (assumes both input lists are sorted ascending and contain comparable items):

(define (sorted-union a b)
  (cond
    ((null? a) b)
    ((null? b) a)
    (else
     (let ((x (car a)) (y (car b)))
       (cond
         ((< x y) (cons x (sorted-union (cdr a) b)))
         ((> x y) (cons y (sorted-union a (cdr b))))
         (else    (cons x (sorted-union (cdr a) (cdr b)))))))))

Test example: (sorted-union '(1 3 5) '(2 3 4)) -> (1 2 3 4 5).

Notes and cautions:

  • For numbers use <, >, and =; eq? is not reliable for numeric equality. For non-numeric elements use appropriate comparators or equal?.
  • If inputs are not sorted, either sort them first or build a result using member/remove-duplicates to avoid duplicates.
  • For very long lists consider a tail-recursive version that accumulates and reverses at the end to avoid stack overflow.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.