user2175783
user2175783

Reputation: 1431

How to Merge 2 lists into one in racket

I have 2 dynamic lists that I would like to merge into one.

Say

'(1 2 3 4)

and

'(15 16)

and get

'(1 2 3 4 15 16)

How can this be done?

Upvotes: 12

Views: 18968

Answers (2)

C. K. Young
C. K. Young

Reputation: 222973

Or, if you're merging two sorted lists and need to maintain the ordering in the result list:

(require srfi/1)
(define (merge-sorted-lists lhs rhs #:order (lt? <))
  (let loop ((result '())
             (lhs lhs)
             (rhs rhs))
    (cond ((null? lhs) (append-reverse result rhs))
          ((null? rhs) (append-reverse result lhs))
          ((lt? (car rhs) (car lhs))
           (loop (cons (car rhs) result) lhs (cdr rhs)))
          (else
           (loop (cons (car lhs) result) (cdr lhs) rhs)))))

Examples:

> (merge-sorted-lists '(1 3 5 7) '(2 4 6 8))
'(1 2 3 4 5 6 7 8)
> (merge-sorted-lists '(7 5 3 1) '(8 6 4 2) #:order >)
'(8 7 6 5 4 3 2 1)

Upvotes: 5

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Use append for this:

(append '(1 2 3 4) '(15 16))
=> '(1 2 3 4 15 16)

Upvotes: 25

Related Questions