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?
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?
Use append
for this:
(append '(1 2 3 4) '(15 16))
=> '(1 2 3 4 15 16)
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)
© 2022 - 2024 — McMap. All rights reserved.