Implement add-leaf, a Scheme procedure that takes in a tree instance t and a number x.
This procedure will return a new tree where for each non-leaf node in the tree, append a new leaf with the label x to that node's branches. If the input tree is a leaf, the resulting tree is unchanged.
Hints:
append will merge the elements in two Scheme lists together. For example, (append (list 1 2) (list 3 4))
results in (1 2 3 4)
map applies a procedure onto every item in a Scheme list. For example, (map - (list 2 4))
results in (-2 -4)
You may find it useful to create a helper lambda function to pass in as the procedure to map
To create a tree with no branches, you must specify nil for its branches. For example, (tree 5 nil)
is a leaf with 5
.
; Constructs tree given label and list of branches
(define (tree label branches)
(if (null? tree)
null
(cons label branches)))
; Returns the label of the tree
(define (label t)
(car t))
; Returns the list of branches of the given tree
(define (branches t)
(cdr t))
; Returns #t if the given tree is a leaf, otherwise return #f
(define (is-leaf t)
(null? (branches t)))
My code:
(define (add-leaf t x)
(if (is-leaf t)
null
(begin
(define mapped-branches
(map (lambda (x) (append (list (x) (branches t))))))
(tree mapped-branches
(label (t))
(append mapped-branches
(branches t)
(add-leaf (branches t) x))))))
It complains that define: not allowed in an expression context in: (define mapped-branches (map (lambda (x) (append (list (x) (branches t))))))