Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started