0

This is my code, which is just a try...

(define-struct cupboard (upperdrawer middledrawer lowerdrawer))

(define-struct room (name furniture))

(define myrooms
  (list
   (make-room "Kitchen"
              (list
               (make-cupboard "Salt" "Sugar" "Pepper")
               (make-cupboard "Tofu" "Sausage" "Beef")))
   (make-room "Bathroom"
              (list
               (make-cupboard "Toothbrush" "Soap" "Shampoo")))
   (make-room "Sleeping room"
              (list
               (make-cupboard "Red Socks" "Blue Socks" "Yellow Socks")
               (make-cupboard "Suits" "Dresses" "Shoes")))))

(define cupboardcontents
  (lambda (myrooms)
    (cond((room? (first myrooms))
          (cupboard? (first myrooms))
          (cupboardcontents (rest myrooms))
         ((cupboard?(first myrooms)) (list
                               (cupboard-upperdrawer myrooms)
                               (cupboard-middledrawer myrooms)
                               (cupboard-lowerdrawer myrooms)))

          ))))

(cupboardcontents myrooms)

Now the task is it to use recursion get a list as output which includes the cupboard contents. Can anybody help here?

1 Answer 1

1

That's actually more tricky that it seems. Here's a try, tell me if you've seen concepts such as named let, then I can expand on it:

(define (cupboardcontents elt)
  (reverse
   (let loop ((elt elt) (res null))
     (cond
       ((null? elt)     res)
       ((room? elt)     (loop (room-furniture elt) res))
       ((cupboard? elt) (list* (cupboard-lowerdrawer elt)
                               (cupboard-middledrawer elt)
                               (cupboard-upperdrawer elt)
                               res))
       ((list? elt)     (loop (cdr elt) (loop (car elt) res)))
       (else            (error "wot?" elt))))))

Testing:

> (cupboardcontents myrooms)
'("Salt" "Sugar" "Pepper" "Tofu" "Sausage" "Beef" "Toothbrush" "Soap" "Shampoo" "Red Socks" "Blue Socks" "Yellow Socks" "Suits" "Dresses" "Shoes")
Sign up to request clarification or add additional context in comments.

4 Comments

We as a reader want to know on named let. It will be awesome I think.
Hey, thanks for your help and sorry for my late answer. Actually it really helped me a little, but the problem was, that in your solution you used commands we are not allowed to use because they were not on our schedule yet (e.g loop or cdr) ;) Maybe next time i will mention that. Thank a lot though!!
loop is not a keyword here, it's the name of an inner procedure; see the link I put into the comments. And I'd be very surprised if cdr was not allowed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.