11. Define a scheme procedure that returns the total number of leaves of a tree For example, (count-leaves '((4 5 6) (1 2) () (3) )) returns 6
Then, trace the procedure with the given example.
Scheme language
solution:
given data:
scheme procedure that returns the total number :
Scheme Code:
(define (count-leaves t)
(cond ((null? t) 0)
((not (pair? t)) 1)
(else (+ (count-leaves (car t))
(count-leaves (cdr t))))))
; The general logic of this function is:
; If the tree is null, return 0
; elif: return 1 if at a leaf. We know
; That we're at a leaf if the position is not null and not a
pair
; else: we are at a pair and must branch our function
; Testing it below:
1 ]=> (load "hierarchical_structures_1.scm")
;Loading "hierarchical_structures_1.scm"... done
;Value: count-leaves
1 ]=> (define tree-1 (cons (list 1 2) (list 3 4)))
;Value: tree-1
1 ]=> tree-1
;Value 11: ((4 5 6)(1 2)()(3)))
1 ]=> (count-leaves tree-1)
;Value: 6
please give me thumb up
Get Answers For Free
Most questions answered within 1 hours.