Hello, I need help finishing up an unzip function which takes a zipped list and returns a list of two lists. The result I want is as follows. . .

(unzip '((a b)(1 2)))
  ((a 1)(b 2))
(unzip '((a 1)(b 2)(c 3)))
  ((a b c)(1 2 3))
(unzip '(unzip '()))
  (() ())

I can get my code to work for the null case and with a list containing two lists, but I'm haveing a hard time figuring out how to make it recursive and work for more than 2 lists such as the second example.

(define (unzip l)
  (if (null? l) '(() ())
    (map list (car l)(car(cdr l)))))

This will work fine for an empty list or two lists, but I'm still new to shcheme and have a hard time setting up the recursive part to work with three or possibly more lists.

Let's think about what the result should look like for a non-empty list. You want a list that contains two lists, right? So the basic structure should be (list something something-else). Now what do we want something and something-else to be? something should be a list that contains the first element of every sublist in l and something-else should be the list that contains the second element of every sublist. You can define both of these just by using the functions you used in your code: map, car and cdr. But instead of using list as the function for map, you should call map twice -- once with car as the function and once with a combination of car and cdr as the function -- and then wrap the two calls to map in list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.