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) '(bc)) 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))))
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.