Functional Problem Solving (CSC 151 2014S) : EBoards

CSC151.02 2014S, Class 37: Trees


Overview

Preliminaries

Upcoming work.

Admin

Extra Credit

Questions on HW

Questions on the Reading

Thinking about trees, starting with lists

What about structures that aren't lists that are built with cons cells

Thinking about trees recursively

First, whole numbers

Lists,

Detour: What is a cons cell?

Defining trees recursively.

A tree of integers

Writing recursive tree procedures

Standard recursive technique:

(define proc
  (lambda (input)
    (if (simple? input)
        (base-case input)
        (combine (computation input) (proc (simplify input))))))

(define proc
  (lambda (lst)
    (if (null? lst)
        (base-case lst)
        (combine (? (car lst) (proc (cdr lst))))))

(define length
  (lambda (lst)
    (if (null? lst)
        0
        (+ 1 (length (cdr lst))))))

Trees have a more complex recursive pattern. You need to recurse on both the car and the cdr.

(define proc
  (lambda (tree)
    (if (pair? tree)
        (combine (proc (car tree)) (proc (cdr tree)))
        base-case)))

Example: Adding the numbers in the tree

(define tree-sum
  (lambda (tree)
    (if (pair? tree)
        (+ (tree-sum (car tree)) (tree-sum (cdr tree)))

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright (c) 2007-2014 Janet Davis, Samuel A. Rebelsky, and Jerod Weinman. (Selected materials are copyright by John David Stone or Henry Walker and are used with permission.)

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.