How to Merge 2 lists into one in racket
Asked Answered
B

2

12

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?

Blunge answered 10/2, 2015 at 19:43 Comment(0)
C
25

Use append for this:

(append '(1 2 3 4) '(15 16))
=> '(1 2 3 4 15 16)
Cameral answered 10/2, 2015 at 19:46 Comment(0)
S
5

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)
Sebastien answered 10/2, 2015 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.