Reputation: 23
I'm a real scheme newbie and i'm trying to work out how to return all the sub-lists given with a list argument (i.e. (1 2 (3 4 5) (6 7 8) 9) should return the two lists (3 4 5) and (6 7 8)).
I know I should be using a recursive function with the rest of the list but I'm having trouble producing the results I want. Here is what I've written: -
(define (find-sublists list)
(cond
((null? list) #t))
(not
(list? (first list)))
(print (first list))
(find-sublists (rest list)))
I'm trying to search through the list and output anything which is a list and then search again, otherwise just recursively search the rest of the list. However I'm not sure how to jump straight to the last line when the condition is met.
Does anybody have any advice for me?
Upvotes: 2
Views: 3136
Reputation: 2038
If you just want to filter out all the lists in a given list, use filter
:
(filter list? '(1 2 (3 4 5) (6 7 8) 9))
or you implement it yourself:
(define (my-filter func lst)
(cond ((null? lst) '())
((func (car lst))
(cons (car lst) (my-filter func (cdr lst))))
(else
(my-filter func (cdr lst)))))
Upvotes: 1
Reputation: 17203
First, I'm assuming that this is a homework assignment; please correct me if I'm wrong.
Next: It looks to me like you have one vital misunderstanding of the problem: it asks you to return the two lists, not to print them.
Next, I'm going to steer you to the How To Design Programs design recipe. Your first step is to write down the data definition that you're working with--I'm not quite sure what it is here, but it might be something like this:
;; a list-of-maybe-lists is either
;; - empty, or
;; - (cons maybe-list list-of-maybe-lists)
;; a maybe-list is either
;; - a list, or
;; - something else
Your next step is to write down a contract and a purpose statement for your program, and then some test cases.
Boilerplate: please forgive me for giving you lots of little steps rather than the answer; the point of all these steps is to enable you to fish for yourself, rather than just waiting for other people to fish for you.
Upvotes: 4