Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DrRacket Combining Lists

I was hoping someone could guide me in the right direction: I am looking two produce all possible combinations of items in two lists:
Example:
Given the lists '(symbol1 symbol2) and '(1 2), I am looking to produce:
(list (list 'symbol1 1) (list 'symbol1 2) (list 'symbol2 1)(list symbol2 2))

My code thus far is:

    (define (combiner list1 list2)
    (list
      (foldr (lambda (a b) (foldr (lambda (c d) (list a c)) empty list1)) empty list2)
      (foldr (lambda (a b) (foldr (lambda (c d) (list b d)) empty list1)) empty list2)))

This clearly isn't working, and neither are a few other methods I've tried. I am having trouble working with the implicit recursion on two lists - any ideas?

like image 330
David Avatar asked Jun 28 '26 07:06

David


2 Answers

What you're looking at here is recursion on two complex arguments, section 17 of How To Design Programs. If you want another hint, I'll tell you which of the three cases this is.

like image 138
John Clements Avatar answered Jun 30 '26 15:06

John Clements


I thought of another possible way to solve the problem. Here's a hint:

(define (combiner list1 list2)
  (define (combine l1 l2)
    (cond ((empty? l1) empty)
          ((empty? l2) XXX)
          (else (cons YYY
                      ZZZ))))
  (combine list1 list2))

In the above piece of code, you'll have to figure out the answer to three questions:

  • XXX How do you advance the recursion when you've finished iterating over the second list, but the first list still has elements, and also you want to advance one element in the first list?
  • YYY How would you combine an element from the first list with an element from the second list?
  • ZZZ How do you advance the recursion when both lists still have elements left, but at this point you're only interested in advancing over the second list?

One last hint: notice that at some point you need to "restart" the second list, for that, you can refer to the original list2, which has not changed at all.

I hope this helps you, I don't want to give you a straight answer (yet) - I want you to figure out the solution by yourself.

like image 23
Óscar López Avatar answered Jun 30 '26 14:06

Óscar López