Given two lists, return a list whose elements are lists of size two, such that for the i
-th list, the first element is the i
-th element of the first original list, and the second element is the i
-th element of the second original list. If one list is smaller than the other, the resulting list is of the smallest size; and so if one of the lists is empty, return an empty list. For example:
> (zip '(1 2) '(3 4))
'((1 3) (2 4))
> (zip '(1 2 3) '())
'()
> (zip '() '(4 5 6))
'()
> (zip '(8 9) '(3 2 1 4))
'((8 3) (9 2))
> (zip '(8 9 1 2) '(3 4))
'((8 3) (9 4))
Try so:
(map cons '(1 2 3) '(a b c))
or so:
(map list '(1 2 3) '(a b c))
(define zip (lambda (l1 l2) (map list l1 l2)))
->(zip '(1 2 3) '(x y z))
'((1 x) (2 y) (3 z))
Because you didn't post the code you've written, I'm guessing this is homework. I'll give you some hints to get started, this is the general structure of the solution, fill-in the blanks - it'll be much more fun if you reach the correct answer by your own means!
(define (zip lst1 lst2)
(cond ((<???> lst1) ; if the first list is empty
<???>) ; then return the empty list
((<???> lst2) ; if the second list is empty
<???>) ; then also return the empty list
(else ; otherwise
(cons (list ; cons a list with two elements:
<???> ; the first from the first list
<???>) ; and the first from the second list
(zip <???> <???>))))) ; advance recursion over both lists
I tested the above implementation with the sample inputs, and the results are as expected:
(zip '(1 2) '(3 4))
=> '((1 3) (2 4))
(zip '(1 2 3) '())
=> '()
(zip '() '(4 5 6))
=> '()
(zip '(8 9) '(3 2 1 4))
=> '((8 3) (9 2))
(zip '(8 9 1 2) '(3 4))
=> '((8 3) (9 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With