scheme

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,)


Solution

  • 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.