I wrote 90% of a tree-map function in scheme, but I encountered a major problem that I am having trouble with. When I test my code with binary tree, all but the first node gets mapped properly. The first node drops out, and I can't seem to think of a way around this. Any advice here as would be appreciated.
(define (value tree)
(car tree))
(define (left tree)
(car (cdr tree)))
(define (right tree)
(car (cdr (cdr tree))))
(define (tree-map f T)
(cond ((null? T) '())
((and (null? (right T))(null? (left T))) '())
((and (null? (right T))(not (null? (left T))))
(make-tree (f (value(left T)))
(tree-map f (left T))
(right T)))
((and (null? (left T))(not (null? (right T))))
(make-tree (f (value(right T)))
(left T)
(tree-map f (right T))
))))
This code is really convoluted. First I don't see an else statement, and a pretty big case drop (if both branches are not null tress). Second why are you worrying if the left or right is null when you have a case already for null trees?
(define (tree-map f T)
(cond ((null? T) '())
(else (make-tree (f (value T))
(tree-map f (left T))
(tree-map f (right T))))))
Being a human compiler is no fun. All you've don with you leaf, empty-left, and empty-right cases is rewrite the same code, but manually drop in the '() where appropriate instead of relying on the function to do it for you.
It seems that there are a couple of errors:
Try this with one of your samples, the question doesn't include all the necessary code to test it myself:
(define (tree-map f T)
; empty tree
(cond ((null? T)
'())
; leaf node
((and (null? (right T)) (null? (left T)))
(make-tree (f (value T)) '() '()))
; empty right subtree
((and (null? (right T)) (not (null? (left T))))
(make-tree (f (value T))
(tree-map f (left T))
'()))
; empty left subtree
((and (null? (left T)) (not (null? (right T))))
(make-tree (f (value T))
'()
(tree-map f (right T))))
; both subtrees are present
(else
(make-tree (f (value T))
(tree-map f (left T))
(tree-map f (right T))))))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.