;; tree.scm ;; ;; An example of representing data in scheme ;; ;; Let's create a tree structure in scheme using (only) cons ;; ... and then access its pieces with (only) car and cdr ;; ... and then write some tools to do things to it. ;; ;; Here's a simple tree : ;; ;; A ;; / \ ;; B C ;; / \ ;; D E ;; ;; To work with this we will ;; ;; (a) pick a representation ... ;; let's have a "node" be a three element list : (value child1 child2) ;; ;; (b) define functions to create & access that representation ;; ;; (c) define function to loop over it for searching, printing, etc ;; ;; Jim Mahoney | Sep 2021 | cs.bennington.college ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; create a node : (define (new-node value left right) (cons value (cons left (cons right '())))) ; i.e. (list . . .) ;; create a node that doesn't have children : (define (leaf-node value) (new-node value '() '())) ;; access the node properties (define (node-value node) (car node)) (define (node-left node) (car (cdr node))) ; i.e. (cadr node) (define (node-right node) (car (cdr (cdr node)))) ; i.e. (caddr node) ;; Now, using those functions ... ;; define a simple tree (define ABCDE (new-node 'A (leaf-node 'B) (new-node 'C (leaf-node 'D) (leaf-node 'E)))) ;; convert a tree to a string (define (tree->string tree) (cond ((nil? tree) "") (else (format #f "[~a ~a ~a]" ; drracket: use (~a "" ...) (node-value tree) (tree->string (node-left tree)) (tree->string (node-right tree)))))) ;; count the nodes in a tree (define (length-tree tree) (cond ((nil? tree) 0) (else (+ 1 (length-tree (node-left tree)) (length-tree (node-right tree)))))) ;; ... and try those functions out (printf "ABCDE is ~a.\n" (tree->string ABCDE)) (printf "ABCDE has ~a nodes.\n" (length-tree ABCDE)) ;; === running this ============================================== ;; ;; $ scheme tree.scm ;; ABCD is [A [B ] [C [D ] [E ]]]. ;; ABCD has 5 nodes. ;;