CS115 - Module 10 - General Trees

Similar documents
Module 9: Trees. If you have not already, make sure you. Read How to Design Programs Sections 14, 15, CS 115 Module 9: Trees

Module 10: General trees

CS115 - Module 8 - Binary trees

Module 9: Binary trees

Module 10: Imperative Programming, Modularization, and The Future

Trees. Binary arithmetic expressions. Visualizing binary arithmetic expressions. ((2 6) + (5 2))/(5 3) can be defined in terms of two smaller

Trees. Readings: HtDP, sections 14, 15, 16.

Trees. Example: Binary expression trees. Example: Evolution trees. Readings: HtDP, sections 14, 15, 16.

Module 8: Binary trees

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

How to Design Programs

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Assignment: 7. Due: Language level: Allowed recursion:

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

CS2500 Exam 2 Fall 2011

CS115 - Module 9 - filter, map, and friends

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

CS115 - Module 4 - Compound data: structures

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

CS 115 Lecture Notes Winter 2019

CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local. CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local 1

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Working with recursion

Graphs. Readings: Section 28. CS 135 Fall : Graphs 1

Intro. Scheme Basics. scm> 5 5. scm>

Graphs. Directed graphs. Readings: Section 28

Module 3: New types of data

CSCC24 Functional Programming Scheme Part 2

Module 8: Local and functional abstraction

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

CS115 - Module 3 - Booleans, Conditionals, and Symbols

Typed Racket: Racket with Static Types

Structure and Interpretation of Computer Programs

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

Typed Scheme: Scheme with Static Types

CS 5010 Program Design Paradigms Lesson 6.1

Chapter 20: Binary Trees

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018

CSE341 Spring 2017, Final Examination June 8, 2017

Structure and Interpretation of Computer Programs

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

User-defined Functions. Conditional Expressions in Scheme

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Homework 6: Higher-Order Procedures Due: 10:00 PM, Oct 17, 2017

Case Study: Undefined Variables

The Typed Racket Guide

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

CSU211 Exam 2 Fall 2007

CSE341 Spring 2017, Final Examination June 8, 2017

Functional Programming. Pure Functional Programming

Macros & Streams Spring 2018 Discussion 9: April 11, Macros

Inductive Data Types

An Introduction to Functions

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

Project 2: Scheme Interpreter

Environments

CS 360 Programming Languages Interpreters

Structure and Interpretation of Computer Programs

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

6.001 Notes: Section 15.1

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

COMP520 - GoLite Type Checking Specification

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

Functions that return lists

CS1102: Macros and Recursion

(Provisional) Lecture 32: Estimated Value, Minimax, Functional Data 10:00 AM, Nov 20, 2017

Functions & First Class Function Values

CMSC 330: Organization of Programming Languages. Operational Semantics

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS

Loops in Scheme, II. (early slides assume map/filter)

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08013 INFORMATICS 1 - FUNCTIONAL PROGRAMMING

Exercise 1: Graph coloring (10 points)

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Unit 10: Data Structures CS 101, Fall 2018

From Templates to Folds

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS INFR08013 INFORMATICS 1 - FUNCTIONAL PROGRAMMING

Proving Properties of Recursive Functions and Data Structures. CS 270 Math Foundations of CS Jeremy Johnson

Note that in this definition, n + m denotes the syntactic expression with three symbols n, +, and m, not to the number that is the sum of n and m.

Higher-Order Functions (Part I)

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 4.1

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

Building a system for symbolic differentiation

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

Propositional Calculus: Boolean Functions and Expressions. CS 270: Mathematical Foundations of Computer Science Jeremy Johnson

Hints for Exercise 4: Recursion

Transcription:

Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Sections 15 and 16.

Arithmetic Expressions Recall with binary trees we could represent an expression containing binary operators (which have exactly 2 arguments), such as ((2 6) + (5 2)) (5 3) But in Racket we are t required to have just 2 arguments. How could we represent (+ (* 4 2) 3 (+ 5 1 2) 2)? We can make a new structure where each node can have any number of children, instead of just 2. + + 3 + 2 5 3 4 2 5 1 2 2 6 5 2 Here we still label each node; the only difference is the number of children.

Representing binary vs general arithmetic expressions Previously, our data definitions were as follows: ;; an Operator is (anyof '+ '- '* '/) (define-struct binode (op arg1 arg2)) ;; a binary arithmetic expression internal node (BINode) ;; is a (make-binode Operator BinExp BinExp) ;; A binary arithmetic expression (BinExp) is either: ;; a Num or ;; a BINode Now we want all same, except: instead of arg1 and arg2, we will use a list: (define-struct ainode (op args)) ;; an arithmetic expression internal node (AINode) ;; is a (make-ainode Operator (listof AExp)) ;; An arithmetic expression (AExp) is either: ;; a Num or ;; a AINode

Representing expressions So given the data definition: (define-struct ainode (op args)) ;; an arithmetic expression internal node (AINode) ;; is a (make-ainode Operator (listof AExp)) ;; An arithmetic expression (AExp) is either: ;; a Num or ;; a AINode How can we represent an expression such as (+ (* 4 2) 3 (+ 5 1 2) 2)? (make-ainode '+ (list (make-ainode '* (list 4 2)) 3 (make-ainode '+ (list 5 1 2)) 2))

Interpreting expressions When we evaluated binary trees we used the following function: ;; (eval-binexp expr) return the value of expr. ;; eval-binexp: BinExp -> Num (define (eval-binexp expr) (cond [(number? expr) expr] ; numbers evaluate to themselves [(symbol=? (binode-op expr) '*) (* (eval-binexp (binode-arg1 expr)) (eval-binexp (binode-arg2 expr)))] [(symbol=? (binode-op expr) '+) (+ (eval-binexp (binode-arg1 expr)) (eval-binexp (binode-arg2 expr)))])) All that is different now is that we have a list of values, args, instead of just arg1 and arg2.

Evaluating Expressions Our code for binary expressions is almost perfect. Instead of evaluating exactly two items, (binode-arg1 expr) and (binode-arg2 expr), then combining them with * or +, we have this list. We need to replace the code: (+ (eval-binexp (binode-arg1 expr)) (eval-binexp (binode-arg2 expr)))])) We need to use evaluate each argument in the list. We could do this recursively. Or use map! (map eval-ainexp (ainode-args expr)) This takes a list of expressions, evaluates each one, and returns the resulting list. But now we need to combine them. Again, we could do this recursively. But we don t need to! Use foldr instead: (foldr + 0 (map eval-ainexp (ainode-args expr)) )

Evaluating Expressions The whole code then becomes: ;; (eval-ainexp expr) return the value of expr. ;; eval-ainexp: AExp -> Num ;; Examples: (check-expect (eval-ainexp (make-ainode '* (list 2 3 5))) 30) (define (eval-ainexp expr) (cond [(number? expr) expr] ; numbers evaluate to themselves [(symbol=? (ainode-op expr) '*) (foldr * 1 (map eval-ainexp (ainode-args expr)) ) ] [(symbol=? (ainode-op expr) '+) (foldr + 0 (map eval-ainexp (ainode-args expr)) ) ] ))

Working with general trees Recalling the following data definition: (define-struct ainode (op args)) ;; an arithmetic expression internal node (AINode) ;; is a (make-ainode Operator (listof AExp)) ;; An arithmetic expression (AExp) is either: ;; a Num or ;; a AINode Exercise: Complete count-leaves. ;; (count-leaves expr) return the number of leaves in expr. ;; count-leaves: AExp -> Nat ;; Examples: (check-expect (count-leaves (make-ainode '+ (list 2 3 (make-ainode '* (list 6 7 42))))) 5)

Mutual Recursion When one function calls a second, and the second calls the first, it is called mutual recursion. Our approach to writing such code is unchanged: write a template for each datatype, based on the data definition; then build functions following the template. Consider: ;; an EvenNat is either ;; 0 or ;; (add1 x) where x is an OddNat. ;; an OddNat is a Nat that is not even. ;; (is-even? n) return #true if n is an ;; EvenNat, otherwise #false. ;; is-even?: Nat -> Bool (define (is-even? n) (cond [(= n 0) #true] [else (is-odd? (sub1 n))])) (define (is-odd? n) (not (is-even? n)))

Mutual Recursion (define-struct ainode (op args)) ;; an arithmetic expression internal node (AINode) ;; is a (make-ainode Operator (listof AExp)) ;; An arithmetic expression (AExp) is either: ;; a Num or ;; a AINode We have defined: 1 AINode, which is defined in terms of (listof AExp) 2 (listof AExp), which is defined in terms of AINode. If we wrote a recursive function evaluate-and-add to work through the (listof AExp), the function would itself call eval-ainexp. But eval-ainexp would call evaluate-and-add. This is a mutually-recursive definition. An example is worked in the official notes. The greater simplicity of the solution using filter and map shows their usefulness!

Leaf Labelled Trees Earlier we worked with trees which had labels on all the nodes. Each node consisted of a (make-node Label (listof Node)); the Label indicating something about the node (in our example, the operator, '+ or '*). We can simplify trees even further by not labelling internal nodes. ;; a leaf-labelled tree (LLT) is a (listof (anyof Num LLT)). (list 2) (list 5 7) (list 2 (list 5 7) 3) (list 2 (list 3 (list 5 7 11))) 2 2 5 7 2 5 7 3 3 5 7 11

Template for Leaf Labelled Trees ;; a leaf-labelled tree (LLT) is a (listof (anyof Num LLT)). Since a LLT is a list, its template comes from the list template, reproduced here: ;; my-listof-x-fun: (listof X) -> Any (define (my-listof-x-fun L) (cond [(empty? L)... ] [else (... (first L)... (my-listof-x-fun (rest L))...)])) Since each item in the list may be a Num or a LLT, we need to distinguish these. We could recognize the LLT using cons?; for an example, see the official notes. Instead, I will identify the leaves using number?. ;; my-llt-fun: LLT -> Any (define (my-llt-fun L) (cond [(empty? L)... ] [(number? (first L)) ;; first is a leaf. (... (first L)... (my-llt-fun (rest L))...)] [else ;; first is not a leaf, so it must be an LLT. (... (my-llt-fun (first L))... (my-llt-fun (rest L))...)]))

;; a leaf-labelled tree (LLT) is a (listof (anyof Num LLT)). ;; my-llt-fun: LLT -> Any (define (my-llt-fun L) (cond [(empty? L)... ] [(number? (first L)) ;; first is a leaf. (... (first L)... (my-llt-fun (rest L))...)] [else ;; first is not a leaf, so it must be an LLT. (... (my-llt-fun (first L))... (my-llt-fun (rest L))...)])) Exercise: Following the template, write a function to count the leaves of a LLT. Exercise: Following the template, complete depth. ;; (depth tree) return the max distance from the root to a leaf of tree. ;; depth: LLT -> Nat ;; Examples: (check-expect (depth (list 6 7)) 1) (check-expect (depth (list 2 (list 3 (list 5)))) 3)

More work with filter, map, foldr... ;; a leaf-labelled tree (LLT) is a (listof (anyof Num LLT)). Complete these exercises without recursion on a list. (You will still need to recurse on the LLT.) Exercise: Write a function to count the leaves of a LLT. Exercise: Complete depth. ;; (depth tree) return the max distance from the root to a leaf of tree. ;; depth: LLT -> Nat ;; Examples: (check-expect (depth (list 6 7)) 1) (check-expect (depth (list 2 (list 3 (list 5)))) 3)

Flattening a list Sometimes we want to extract the leaves from a leaf-labelled tree. For example: 2 3 5 7 11 (list 2 3 5 7 11) Exercise: Complete flatten. Hint: use the append function. ;; (flatten tree) return the list of leaves in tree. ;; flatten: LLT -> (listof Num) ;; Examples: (check-expect (flatten (list 1 (list 2 3) 4)) (list 1 2 3 4)) (check-expect (flatten (list 1 (list 2 (list 3 4)))) (list 1 2 3 4))

Module summary Be able to work with general trees and leaf-labelled trees. Write programs that use recursion on trees, and either recursion or higher order functions on lists within the trees. Create templates from data definitions. Use data definitions and templates to guide design of functions, both recursive and non-recursive.

Wrapping up CS115 I want to highlight: The importance of communication, to other programmers but even to yourself. That data definitions can guide the design of our programs. These big ideas transcend language. They will influence your work in CS116 and beyond.

Looking ahead to CS116 CS116 uses Python. The syntax of this language is less restricted, which means There are more ways to say things (which makes things easier to say!) There are more ways to say things (there is more syntax to learn) We will work on Writing programs that are longer, or deal with large amounts of data Designing programs so they run efficiently

Options for continuing CS CS major: Take CS 116 and then CS 136. Talk to a CS advisor about the process. Many students have been successful in CS after starting in CS 115. Computing Technology Option: Take CS 116. Talk to an advisor to understand your choices. Note: Participate in course selection! Otherwise, you may not be able to enroll in your preferred courses.