John
John

Reputation: 837

Scheme merge two lists into one

how to design a function that merge two lists into one list. the first element of first list will be the first element of the new list and the first element of the second list will be the second element of the new list (a,b,c,d,e,f) (g,h,i) will be (a,g,b,h,c,i,d,e,f,)

Upvotes: 5

Views: 22358

Answers (4)

Dan Grahn
Dan Grahn

Reputation: 9414

This can be done using a simple condition.

(define (merge a b)
  (cond ((null? a) b)
        ((null? b) a)
        (else (cons (car a) (merge b (cdr a))))
        ))

Upvotes: 1

wolrah
wolrah

Reputation: 19

There is no need to check both lists: Here is a simple version:

    (define (interleave lx lz)
  (cond
    [(empty? lx) lz]
    [else (cons (first lx)(interleave lz (rest lx)))]))


(check-expect(interleave '() '())'())
(check-expect(interleave '(X X X X X X) '(O O O O O))
             (list 'X 'O 'X 'O 'X 'O 'X 'O 'X 'O 'X))
(check-expect(interleave '(1 2 3) '(a b c d e f))
             (list 1 'a 2 'b 3 'c 'd 'e 'f))

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

The procedure you're trying to implement is known as interleave or merge. Because this looks like homework, I can't leave you a straight answer, instead I'll point you in the right direction; fill-in the blanks:

(define (interleave lst1 lst2)
  (cond ((null? lst1)     ; If the first list is empty
         <???>)           ; ... return the second list.
        ((null? lst2)     ; If the second list is empty
         <???>)           ; ... return the first list.
        (else             ; If both lists are non-empty
         (cons (car lst1) ; ... cons the first element of the first list
               <???>))))  ; ... make a recursively call, advancing over the first
                          ; ... list, inverting the order used to pass the lists.

Upvotes: 8

Aslan986
Aslan986

Reputation: 10324

Here is a purely functional and recursive implementation in R6RS

(define (merge l1 l2)
      (if (null? l1) l2
          (if (null? l2) l1
              (cons (car l1) (cons (car l2) (merge (cdr l1) (cdr l2)))))))

Upvotes: 13

Related Questions