Created
January 9, 2012 18:35
-
-
Save zallarak/1584263 to your computer and use it in GitHub Desktop.
Counting the leaves in a tree in Scheme (Lisp)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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: ((1 2) 3 4) | |
1 ]=> (count-leaves tree-1) | |
;Value: 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to do a iterator version?