about summary refs log tree commit diff stats
path: root/js/games/nluqo.github.io/~bh/61a-pages/Lectures/2.2/tree.scm
blob: eec7e50d89243b1fb5ca62c3cdd0f073c2663ceb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
;;; Implementation of tree ADT
;;;
;;; Data at leaves only; leaves are words.

(define (make-tree datum children)
  (cond ((null? datum) children)
	((not (null? children)) (error "datum at branch node!"))
	((list? datum) (error "datum must be a word!"))
	(else datum)))

(define (datum node)
  (if (list? node)
      '()
      node))

(define (children node)
  (if (list? node)
      node
      '() ))

(define (leaf? node)
  (not (pair? node)))

;; or can do:
;; (define (leaf? node)
;;  (null? (children node)) )

;; Map a function over the data of a tree

(define (treemap fn tree)
  (cond ((null? tree) '())
	((leaf? tree) (fn tree))
	(else (make-tree '() (map
			      (lambda (t) (treemap fn t))
			      (children tree))) )))

;; Sample

(define (square x) (* x x))

(define t1 '((1 2) 3 (4 (5 6))))

(treemap square t1)