0
votes

I'm supposed to create a function called ( merge-list lst1 lst2) that alternately picks elements from one of the two input lists and creates a new list. For example the output of (merge-list ‘(2 4) ‘(b c)) is '(2 b 4 c). Here's what I have so far, but when I compile I am receiving the "application:not a procedure" error

 (define (merge-list lst1 lst2)

(cond ((null? lst1) lst2)

 ((null? lst2) lst1))

  (append( append(list(car lst1) list(car lst2)))list-shuffle((cdr lst1)(cdr lst2))))
1
You should get the basics right. In Scheme we don't call a function like this: list-shuffle(lst1 lst2). The correct way (and do mind the parentheses!) is: (list-shuffle lst1 lst2).Óscar López

1 Answers

2
votes

The solution is simpler than you think, we don't even have to use append - in fact, you should avoid using append, whenever possible use cons for building an output list: this is because append does more work and can potentially lead to O(n^2) solutions. Try this instead:

(define (merge-list lst1 lst2)
  (cond ((null? lst1) lst2)    ; if the first list is empty, return the second
        ((null? lst2) lst1)    ; if the second list is empty, return the first
        (else (cons (car lst1) ; otherwise `cons` the first element of the first list
                    (merge-list lst2 (cdr lst1)))))) ; and interleave the lists

It works as expected for lists of the same length:

(merge-list '(2 4) '(b c))
=> '(2 b 4 c)

(merge-list '(2 4 6) '(b c d))
=> '(2 b 4 c 6 d)