patternMinor
Abstract tree-map function
Viewed 0 times
mapabstractfunctiontree
Problem
Exercise 2.31. Abstract your answer
to exercise 2.30 to produce a
procedure tree-map with the property
that square-tree could be defined as
I wrote the following solution:
Can this be improved in any way?
to exercise 2.30 to produce a
procedure tree-map with the property
that square-tree could be defined as
(define (square-tree tree) (tree-map square tree))I wrote the following solution:
(define (square x) (* x x))
(define (tree-map f tree)
(cond ((null? tree) null)
((pair? tree)
(cons (tree-map f (car tree))
(tree-map f (cdr tree))))
(else (f tree))))
(define (map-tree-map f tree)
(map (lambda (subtree)
(if (pair? subtree)
(cons (map-tree-map f (car subtree))
(map-tree-map f (cdr subtree)))
(f subtree)))
tree))
(define (square-tree tree) (tree-map square tree))
(define (map-square-tree tree) (map-tree-map square tree))
(define a (list 1 1 (list (list 2 3) 1 2)))Can this be improved in any way?
Solution
Your direct definition of
The version using
tree-map looks good.The version using
map may be written more succinctly (with the recursive portion factored out) as follows:(define (tree-map f tree)
(define (rec tree)
(map (lambda (subtree)
((if (pair? subtree) rec f) subtree))
tree))
(rec tree))Code Snippets
(define (tree-map f tree)
(define (rec tree)
(map (lambda (subtree)
((if (pair? subtree) rec f) subtree))
tree))
(rec tree))Context
StackExchange Code Review Q#1733, answer score: 2
Revisions (0)
No revisions yet.