Write a procedure depth that takes as argument an arbitrarily deeply nested list
ID: 3791165 • Letter: W
Question
Write a procedure depth that takes as argument an arbitrarily deeply nested list and returns the maximum depth of any of its sublists: the depth of an object in a list is the number of cars that can be applied to it, not necessarily in a row... (You may wish to use the built-in max function for this). E.g.: (depth 'a) rightarrow 0 (depth '(a)) rightarrow 1 (depth '(a (b) c)) rightarrow 2 (depth '(((((a((b))))))) - 8 Write a map function treemap for trees, analogous to the built-in map for flat lists. This function should apply a procedure to even' element of the tree and return the results in a tree of the same shape as the original. Eg.: (treemap sqr '(1 (2 3) ((4 5) (6 7)) (((8 (9)))))) rightarrow (1 (4 9) ((16 25) (36 49)) (((64 (81))))) Write a function flattenList that takes a tree as an argument and returns a list of the leaf values of the tree. E.g.: (flattenList '(1 (2 3) ((4 5 6 (7)))(((8 (9)))))) rightarrow (123456789)Explanation / Answer
(#%require (only racket/base random))
; Question 6
; a)
(define (depth lis)
(define (inner-depth li currDepth maxDepth)
(if (null? li)
(+ maxDepth 1)
(if (list? li)
(if (list? (car li))
(inner-depth (car li) (+ 1 currDepth) maxDepth)
(inner-depth (cdr li) currDepth (max currDepth maxDepth)))
0)))
(inner-depth lis 0 0))
; b)
(define (treemap procedure lis)
(if (null? lis)
'()
(if (list? lis)
(cons (treemap procedure (car lis))(treemap procedure (cdr lis)))
(procedure lis))))
;(treemap sqr '((1) 2 3 ((4 5 6) 7) 8 9))
(define (sqr x) ; for testing
(* x x))
; c)
(define (flattenList lis)
(if (null? lis)
'()
(if (list? lis)
(append (flattenList (car lis))(flattenList (cdr lis)))
(list lis))))
;(flattenList '(1 (2 3) ((4 5 6 (7)))(((8 (9))))))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.