CS275
Higher Order Functions
Due at midnight at the end of Wednesday, October 10. MONDAY, October 15. sigh.
The goal for this assignment is to give you a deeper understanding of recursion, particularly on complex structures
In each of the following you can use either of the folds we have discussed: foldl or foldr
For the rest of this assignment you will write a number of procedures that involve trees. Recall that a tree is a data structure that is either empty, or contains some data and has a list of children, each of which is a tree.
We will use Scheme procedures to implement the data type. At the beginning of the following section the tree datatype will be defined. All of this code is contained in the file "TreeDatatype.rkt".
#lang racket
(require "TreeDatatype.rkt")
You will need to download the file TreeDatatype.rkt Please include this file in your handin folder.
A tree is either
(define tree? (lambda (t) (or (empty-tree? t) (non-empty-tree? t))))
(define empty-tree? (lambda (x) (null? x)))
(define non-empty-tree? (lambda (x)
(cond
[(list? x) (eq? (car x) 'tree)]
[else #f])))
; constructors
(define non-empty-tree (lambda (value list-of-children)
(list 'tree value list-of-children)))
(define empty-tree (lambda () null))
; Convenience constructor
(define makeTree (lambda l
(non-empty-tree (car l) (cdr l))))
; utility functions
(define value (lambda (tree)
(cond
[(empty-tree? tree) 'error]
[else (cadr tree)])))
(define list-of-children (lambda (tree)
(cond
[(empty-tree? tree) 'error]
[else (caddr tree)])))
(define number-of-children (lambda (tr)
(cond
[(empty-tree? tree) 'error]
[else (length (list-of-children tr))])))
(define leaf? (lambda (tr)
(cond
[(empty-tree? tree) 'error]
[else (zero? (number-of-children tr))])))
; example trees
(define Empty (empty-tree))
(define T1 (makeTree 50))
(define T2 (makeTree 22))
(define T3 (makeTree 10))
(define T4 (makeTree 5))
(define T5 (makeTree 17))
(define T6 (makeTree 73 T1 T2 T3))
(define T7 (makeTree 100 T4 T5))
(define T8 (makeTree 16 T6 T7))
For example, here is a picture of T8 showing the others as subtrees:
All of this code is in file TreeDatatype.rkt
In the exercises that follow, you should use higher-order functions like map, apply, and fold to make your solution as concise as possible. You should also use letrecto define any recursive help functions.
All programs should be written using the tree operators defined above. Don't directly manipulate the list representations; use the tree procedures.
As usual, if the solution to an earlier problem is useful in a later one, go ahead and use it.
In all of these tr is a value of the tree datatype
(childSum tr) This returns the sum of the values in the children of the given node. The tree is assumed to be non-empty.
(childSum T8) returns 173;
(childSum T6) returns 82.