Question: Scheme Language a. Write a function level that takes a tree and a level index as arguments and returns all items from the tree that
Scheme Language
a. Write a function level that takes a tree and a level index as arguments and returns all items from the tree that exist at the given level (in a single list). A level, i, in a tree is the set of all nodes in the tree with depth = i. E.g.:
(level 1 '(1 (2 3 4) 5 (6 (7 8) 9))) '(1 5) (level 2 '(1 (2 3 4) 5 (6 (7 8) 9))) '(2 3 4 6 9) (level 3 '(1 (2 3 4) 5 (6 (7 8) 9))) '(7 8)
b. Write a function called tree-filter for trees that is analogous to the built-in filter for flat lists (see below). This function should apply a predicate to every element of the tree, keeping only those that pass, and return the results in a tree of the same shape as the original. E.g.:
(tree-filter even? '(1 (2 3) ((4 5) (6 7)) (((8 (9)))))) ((2) ((4) (6)) (((8 ()))))
(define (filter predicate sequence) (cond ((null? sequence) '()) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence)))))
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
