for a function that should work in an arbitrary nested list. It’s easy for me to first write a version with a flat list (in our case it’s an odd filter), and then edit it to create a nested version (I will call it an odd filter *)
First for a regular odd filter
(define filter-odd
(lambda (ls)
(cond
[(null? ls) '()]
[(odd? (car ls)) (cons (car ls) (filter-odd (cdr ls)))]
[else (filter-odd (cdr ls))])))
Now for filter-odd * (one right side will be left as an exercise (although it seems like you know the answer from your question))
(define filter-odd*
(lambda (ls)
(cond
[(null? ls) '()]
[(list? (car ls)) #| Do something with both car and cdr of ls |# ]
[(odd? (car ls)) (cons (car ls) (filter-odd* (cdr ls)))]
[else (filter-odd* (cdr ls))])))
As a note, this design pattern can be used to write any recursive program and convert it from working only with flat lists to work with arbitrarily deep lists.
source
share