I'm new to Scheme and I'm trying to write a procedure which combines n list into a list of n-tuples. If the lists are of different size, the tuples should contain the empty list ()
when the corresponding list ran out of elements.
My current implementation is the following:
(define (comb list1 list2)
(cond [(empty? list1) empty]
[(empty? list2) empty]
[else (cons (list (first list1) (first list2))
(comb (rest list1) (rest list2)))]))
However, this program doesn't produce another tuple when there are no more items in the list to combine. For instance, (comb '(1 2 3 ) '(3 4))
produces only ((1 3) (2 4))
How do I solve it?
Let's split the problem into 2 parts.
First let's assume a procedure that will take a list, and return the following results:
An example implementation could be:
Testing:
Now using this procedure we create the main procedure that will just loop until all sublists are empty:
Testing:
You need to specifically deal with the situation where one of the lists is empty. The following does what I think you want with two lists.
This is a bit tricky, and I believe it's not an appropriate exercise for someone who is just learning the basics of the language. Anyway, here's my proposed solution, in terms of higher-order procedures:
The trick was to find the maximum length of the lists and then build new lists with that length, filling them with
'()
at the end. After that, it's a simple matter of building the answer by taking one element from each sublist. It works as expected: