Skip to content

Instantly share code, notes, and snippets.

@zallarak
Created January 9, 2012 18:35
Show Gist options
  • Save zallarak/1584263 to your computer and use it in GitHub Desktop.
Save zallarak/1584263 to your computer and use it in GitHub Desktop.
Counting the leaves in a tree in Scheme (Lisp)
(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
@suguanYang
Copy link

how to do a iterator version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment