Scheme: Compound Data Chapter 6 of HTDP Ms. Knudtzon September 19.

Slides:



Advertisements
Similar presentations
Higher-Order Functions and Loops c. Kathi Fisler,
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
Scheme: Functions Chapter 3 of HTDP Ms. Knudtzon September 12.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
Basics of Computer Programming Web Design Section 8-1.
The Data Design Recipe CS 5010 Program Design Paradigms “Bootcamp” Lesson © Mitchell Wand, This work is licensed under a Creative Commons.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 2: Structured.
Multi-way Trees CS 5010 Program Design Paradigms “Bootcamp” Lesson 6.6 © Mitchell Wand, This work is licensed under a Creative Commons Attribution-NonCommercial.
Mrs. Chapman. Tabs (Block Categories) Commands Available to use Script Area where you type your code Sprite Stage All sprites in this project.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
CSC 160 Computer Programming for Non-Majors Chapter 6: Structures Prof. Adam M. Wittenstein
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
CS 330 Programming Languages 09 / 13 / 2007 Instructor: Michael Eckmann.
Section 6.1: Structures (continued). Example 1: in-left-side? ; Purpose: To determine whether a point is in the leftmost 150 pixels of the screen. ; Contract.
The Design Process/Recipe An example over list of circles c. Kathi Fisler, 2001.
CSC 160 Computer Programming for Non-Majors Lecture #10: Conditionals I Prof. Adam M. Wittenstein
CS 201 Functions Debzani Deb.
Chapter 8: Introduction to High-level Language Programming Invitation to Computer Science, C++ Version, Third Edition.
1 Committed to Shaping the Next Generation of IT Experts. Chapter 3 – Graphs and Charts: Delivering a Message Robert Grauer and Maryann Barber Exploring.
CSC 160 Computer Programming for Non-Majors Chapter 3: Programs are Functions Plus Variable Definitions Prof. Adam M. Wittenstein
Structural Decomposition CS 5010 Program Design Paradigms “Bootcamp” Lesson 2.1 © Mitchell Wand, This work is licensed under a Creative Commons.
Chapter 8: Introduction to High-level Language Programming Invitation to Computer Science, C++ Version, Third Edition.
Chapter 2: Algorithm Discovery and Design
Chapter 2: Algorithm Discovery and Design
Mathematics Vocabulary – Grade K add ©Partners for Learning, Inc. To bring two or more numbers or things together to make a new total.
Introducing General Recursion CS 5010 Program Design Paradigms “Bootcamp” Lesson 8.2 TexPoint fonts used in EMF. Read the TexPoint manual before you delete.
Mutually-Recursive Data Definitions CS 5010 Program Design Paradigms “Bootcamp” Lesson 6.4 © Mitchell Wand, This work is licensed under a Creative.
Mr. Wortzman. Tabs (Block Categories) Available Blocks Script Area Sprite Stage All sprites in this project.
TeachScheme, ReachJava Adelphi University Tuesday afternoon June 23, 2009.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 5 Sept 4th, 2001 Fall Semester.
Arbitrarily Long Data Structures: Lists and Recursion CMSC Introduction to Computer Programming October 4, 2002.
Scheme: Lists Cont’d Chapter 9-10 of HTDP Ms. Knudtzon September 26.
The Data Design Recipe CS 5010 Program Design Paradigms “Bootcamp” Lesson © Mitchell Wand, This work is licensed under a Creative Commons.
Invitation to Computer Science, Java Version, Second Edition.
TeachScheme, ReachJava Adelphi University Tuesday afternoon July 13, 2010.
Examining Two Pieces of Data CS 5010 Program Design Paradigms “Bootcamp” Lesson © Mitchell Wand, This work is licensed under a Creative.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
CSC 160 Computer Programming for Non-Majors Chapter 8: Scheme Language Review Prof. Adam M. Wittenstein
Compound Data. Last Lecture Booleans Only two elements Symbols Not to be confused with variables Strings Notions of equality on values.
CS 330 Programming Languages 11 / 13 / 2008 Instructor: Michael Eckmann.
Design Strategies 2: Using a template CS 5010 Program Design Paradigms “Bootcamp” Lesson 2.1 © Mitchell Wand, This work is licensed under a Creative.
Rewriting your function using map and foldr CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual.
Lists of Structures CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual before you delete this.
Functional Programming Language 1 Scheme Language: part 2.
Destructor Templates CS 5010 Program Design Paradigms “Bootcamp” Lesson
Lecture on Set! And Local CS 2135 Copyright Kathi Fisler, 2002 This material requires Advanced Language Level.
Halting Measures and Termination Arguments CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual.
CS CS1321: Introduction to Programming Georgia Institute of Technology College of Computing Lecture 6 Sept 6th, 2001 Fall Semester.
LISTS. LEARNING OBJECTIVES Create a block that accepts a parameter Create a block that returns a value Create scripts that manipulates lists Incorporate.
The Last Lecture CS 5010 Program Design Paradigms "Bootcamp" Lesson © Mitchell Wand, This work is licensed under a Creative Commons Attribution-NonCommercial.
Using the List Template CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual before you delete.
Using the List Template CS 5010 Program Design Paradigms “Bootcamp” Lesson 4.2 TexPoint fonts used in EMF. Read the TexPoint manual before you delete this.
Sometimes Structural Recursion Isn't Enough CS 5010 Program Design Paradigms “Bootcamp” Lesson 8.1 TexPoint fonts used in EMF. Read the TexPoint manual.
Midterm Review CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.:
Solving Your Problem by Generalization CS 5010 Program Design Paradigms “Bootcamp” Lesson © Mitchell Wand, This work is licensed under.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Functional Programming Language 1 Scheme Language: part 3.
CS 5010 Program Design Paradigms “Bootcamp” Lesson 2.2
CS 5010 Program Design Paradigms “Bootcamp” Lesson 5.2
CS 5010 Program Design Paradigms “Bootcamp” Lesson 1.3
CS 1321.
Expanded Recursive Diagrams OCAML rapid tour, day 2
Solving Your Problem by Generalization
CS 5010 Program Design Paradigms “Bootcamp” Lesson 6.5
Let's Play "What's the Question"
More examples of invariants
Rewriting your function using map and foldr
Lisp.
Examining Two Pieces of Data
Presentation transcript:

Scheme: Compound Data Chapter 6 of HTDP Ms. Knudtzon September 19

Checkpoint Homework: check-color Exercise

Introduction Rarely do we have such simple data that we can represent it with a single number, string, symbol, or boolean  Usually we have several pieces of data about one object that we are interested in Example: A cd with artist name, title, price, etc  We compound several pieces of data into one In Scheme, this is a structure

Representing Pixels A pixel is like a Cartesian point, with x & y coordinates (but the y direction is downwards) In Scheme, there is a posn structure that combines two numbers  To create a posn: (make-posn 3 4)  To get the individual numbers back: (posn-x myPosn) (posn-y myPosn)

Distance to 0 Let’s write a function that computes how far a pixel is from the origin ;; distance-to-0: posn --> number ;; computes distance of a-posn to the origin ;; Example: (distance-to-0 (make-posn 8 6)) = 10 (define (distance-to-0 a-posn) What is our next step?  Let’s start with what we know about the data

Distance Function (define (distance-to-0 a-posn) … (posn-x a-posn) … … (posn-y a-posn) … ) This is basically our template for any posn function - then we can just fill in the parts that are specific to this specific problem: (define (distance-to-0 a-posn) (sqrt (+ (sqr (posn-x a-posn)) (sqr (posn-y a-posn))))) ;; Test Cases should follow

Structure Definitions You’ve seen how to use an already defined structure, but how do you create your own structures? Let’s look at how posn is written as an example

Posn Definition (define-struct posn (x y)) When DrScheme evaluates this definition, it automatically creates three operations for use to create data and to program:  make-posn, the constructor, which creates posn structures  posn-x, a selector, which extracts the x coordinate  posn-y, a selector, which extracts the y coordinate

Another Example (define-struct entry (name zip phone)) To use: (make-entry “Ms. K” ‘ ) (define x (make-entry “Ms. K” ‘ )) Think of the structure as a box with a compartment for each field: And you can access each compartment separately: (entry-name x) or (entry-zip x) or (entry-phone x) Name: Ms. K Zip: Phone: x Just gives the struct a name

Formalizing Matters What if we said: (define p (make-posn ‘Albert ‘Einstein)) and then tried to use the “posn” with: (distance-to-0 p) We would get errors! So we need to formalize how we intend to use out structures and how we construct the elements of those structures  We do this with a Data Definition

Data Definition Combination of English and Scheme that is the contract for that structure  Scheme doesn’t check the contract, but you assume that users of your structure or functions will follow what you have specified For example, we would say ; A posn is a structure ; (make-posn x y) ; Where x and y are numbers

Design Recipe Let’s see how the Design Recipe scales to make it easy to think out the problems for programs with structures Data Definition Examples of Data Template Contract & Purpose Examples (Test Cases) Header and Body

Data Definition Search the problem statement for descriptions of the objects needed and design data representations based on that (define-struct student (last first teacher)) ; A student is a structure: (make-student l f t) where l, f & t ; are symbols Or a shortcut I use: (define-struct student (last first teacher)) ; A student is a structure: (make-student symbol symbol symbol)

Examples of Data Then show (or define) the kinds of data that are acceptable with your data definition (make-student ‘henry ‘mills ‘Ms.K) (define nickI (make-student ‘nick ‘ink ‘Ms.K)) (define nickM (make-student ‘nick ‘m ‘ms.k))

Template A function that inputs a structure is likely to compute its results from the components of the structure, so it helps to start with those (using the selector expressions) ;; student-func: student --> ???? ;; purpose: (define (student-func aStudent) … (student-last aStudent) … … (student-first aStudent) … … (student-teacher aStudent) … )

Rest of Recipe Contract & Purpose: do these for the specific functions you are writing Examples: Write examples (test cases) for the function  Use the data examples you wrote earlier (that’s why I recommend using the defines) (my-s-func nickM) Header & Body: Using the template, formulate an expression that computes the answer from the available data and other Scheme functions

Putting It All Together Class Exercise: Create data for boas containing name, length, what they eat  Write a function isShorter? that determines whether a boa is shorter than a given amount Design Recipe  Data Definition  Examples Of Data  Template  Contract & Purpose  Examples (Test Cases)  Header & Body

Scheme Mini-Project Draw Teachpack: Introduces simple graphics operations using posn structures  draw-solid-line: posn posn  draw-solid-rect: posn number number color  draw-solid-disk: posn number color  draw-circle: posn number color Each operation produces boolean Each has a matching clear- operation Your Scheme mini-project (see project handout) will use this drawing package

Scheme: Mixed Data Chapter 7 of HTDP Ms. Knudtzon September 20

Checkpoint 80-point Quiz #3

Graphical Test Cases Special > Insert Test Case

Structures Yesterday our structures were made up of symbols, numbers, booleans & strings Today, let’s consider structures that can be made of other structures We will also look at how to do some error checking in our functions to make sure we get the expected kind of data

Distinguishing Data The other day, I introduced the symbol? and string? operators called predicates  They recognize particular kinds of data  Also available: number? boolean? struct? For each structure that we make, Scheme also makes a predicate  posn?  student?  boa?  Etc So any function we write can check the type of its inputs

Mixed Data We can have one name refer to multiple types of data Yesterday we defined a dillo and a boa Let’s do a data definition for an animal ; An animal is either ; a boa structure: ; (make-boa symbol number), or ; a dillo stucture ; (make-dillo symbol number number boolean)

Animal-func So given that we can use predicates to distinguish our data, let’s make a template for animal data ; animal-func: animal --> ??? (define (animal-func an-ani) (cond [(boa? an-ami) … (boa-name an-ami) (boa-length an-ami) (boa-food an-ami) … ] [(dillo? an-ami) … (dillo-name an-ami) (dillo-age an-ami) (dillo-timesRunOver an-ami) (dillo-dead? an-ami) … ]))

New template Make a cond block to distinguish the different kind of available data Pull out the available data for each case Then you can put this all in a comment box When you need to write a new function, you can copy the template, fill in the blanks and erase the stuff you don’t need anymore

Animal Function Let’s add a length field to the dillo definition so that we could compare animal lengths Using our template, we could then create a new animal function, tooShort? which takes an animal and returns true if the boa is shorter than 6 or 2 for a dillo

Another Example Lets define a shape class which can be circle or square structures (which also need to be defined), each of which require a posn and a number  The posn is the circle’s center and the upper left corner of the square  The number is the circle’s radius and the square’s length Follow the design recipe to sketch out everything for a shape  Then write a perimeter function for a shape

Scheme: Mixed Data Cont’d and Lists Chapter 7 & 9 of HTDP Ms. Knudtzon September 21

Shapes Continued Lets define a shape class which can be circle or square structures (which also need to be defined), each of which require a posn and a number  The posn is the circle’s center and the upper left corner of the square  The number is the circle’s radius and the square’s length Follow the design recipe to sketch out everything for a shape  Then write a perimeter function for a shape

Error checking Note: the predicates (type questions) that we have been using to check type for functions could also be used for simple input checking If we expect a function to only receive numbers and we get something else, we could cause an error, which input a symbol (the function name) and a string (the error message you want displayed) (define (my-func foo) (cond [ (number? foo) …] [ else (error ‘my-func “number expected”)])) This way you aren’t returning something that isn’t expected (like a string message when the function contract says it returns a number)

Lab Exercise (Homework) Develop structure and data definitions for a collection of vehicles. The collection should include at least buses, limos, cars, and police- cars. All vehicles should have a licensePlate, milesDriven, and gasTankCapacity. Add a structure-specific attribute for each class of vehicle. Then develop a template for functions that inputs a vehicle. Expanding on the template, write a function that checks the license plate of a vehicle against a “wantedVehicle” and returns true if it is a match (inputting two vehicles to the function) Make another function that calculates the miles per gallon that a given vehicle has gotten, assuming it has used a whole tank.

Lists The wonderful world of arbitrary-length structures

Lists We all understand what a list is - we make them all the time So the question is how do we make these lists in Scheme? When we form a list, we always start with the empty list and then we add elements to it

Lists in Scheme In Scheme, the empty list is simply: empty And then to construct a longer list, we use the cons operator: (cons “Buy milk” empty) First “Buy milk” rest empty

And again To add more items, we keep using cons again: (cons “Water plants” (cons “Buy milk” empty)) First “Buy milk” rest empty restFirst “Water plants” Etc

Lists of Numbers We can makes lists of anything - here’s a list of 10 numbers: (cons 0 (cons 1 (cons 2 (cons 3 (cons 4 (cons 5 (cons 6 (cons 7 (cons 8 (cons 9 empty ))))))))))

Mixed Data Lists Lists can also have values of multiple kinds: (cons ‘APCS (cons 3 (cons “testing testing” (cons true empty))))

Using Lists Let’s says we are given a list a numbers and we want to add the numbers on the list. How do we do this? For simplicity, let’s say that we only have a list of three numbers ;; A list-of-3-nums is ; (cons x (cons y (cons z empty))) ;; where x, y, and z are numbers

Writing add-up-3 ;; add-up-3: list-of-3-nums --> number ;; to add up 3 numbers in a list ;; example/test case: ;; (= (add-up-3 (cons 2 (cons 1 (cons 3 empty)))) 6) (define (add-up-3 mylist) …)

Selectors for lists first and rest are the operators we need to pull out parts of a list The data definitions for first and last are:  ;; first: non-empty-list --> value  ;; rest: non-empty-list --> list (define li (cons 10 (cons 20 (cons 5 empty))) What is:  (rest li)  (first (rest li))  (rest (rest li))  (first (rest (rest li)))  (rest (rest (rest li)))

Add-up-3 So what do we need to do here? ;; add-up-3: list-of-3-nums --> number ;; to add up 3 numbers in a list ;; example/test case: ;; (= (add-up-3 (cons 2 (cons 1 (cons 3 empty)))) 6) (define (add-up-3 mylist) …)

List Data Definitions We need a way to describe the lists we want to store and the kind of data they store.  The data definitions good references and they remind us how to build data Example: ;; A list-of-symbols is either: ; the empty list, empty, or ; (cons s los) where s is a symbol and los is a list of symbols Note here we have the data definition referring back to itself

LOS or LOST?? ;; A list-of-symbols is either: ; the empty list, empty, or ; (cons s los) where s is a symbol and los is a list of symbols How does this work? Does it make sense?  We can construct elements from it (the data definition)  It works for any cases of our list that we can think of

Using the Design Recipe Everything is as before, but the template needs to have cond- expressions for each clause in the data definition  In the case of a list, empty and cons ;; General Template for list-of-symbols ;; alos-func: list-of-symbols --> ??? (define (alos-func alos) (cond [ (empty? alos) … ] [ (cons? alos) … (first alos) … … (alos-func (rest alos)) …. ])) Same number of arrows as in data definition

LOS Function Example 1 ;; length : list-of-symbols --> number ;; consumes a list of symbols and returns ;; the number of items in the list (define (length alos) … ) Try this together in Scheme

Homework Lab Exercise from yesterday (Vehicle Structures) Review lengthof function from class

(Thursday Lecture) Review and practice on the whiteboard about lists and list functions Individual students should have notes

Scheme: Lists Cont’d Chapter 9-10 of HTDP Ms. Knudtzon September 23

Checkpoint 80 point quiz #4b (instead of yesterday’s) List exercises  dollar-store?  delta  check-range1?  check-range?  average-price we will do together

Average-price Note: This next one requires some additional thought. Make sure that you do the test cases before writing the method and pay attention to what actions you are doing to calculate the result. Exercise Define the function average-price. It consumes a list of toy prices and computes the average price of a toy. The average is the total of all prices divided by the number of toys. Iterative Refinement: First develop a function that works on non-empty lists. Then produce a checked function that signals an error when the function is applied to an empty list.

What is recursion? In Computer Science, recursion is typically defined as self-reference (having a function/method call itself) Fractals are a visual example of recursion  Each small part is a replica of the original part  A “self-similar” structure that can be seen at different levels of detail

Fractals Julia Set Romanesco broccoli

Recursion In mathematics and computer science, we use recursion as an elegant way to approach problem solving  You can reduce the number of steps in a problem solution if the steps all do the same thing  It’s a way to solve a problem by basing the solution on the known result of a “smaller” problem In Scheme, we’ve seen lists, in which the way we define the data is recursive  So the recursive functions (problem-solving) just “fall-out” from the templates which are based on the data definitions

List Project The person responsible for counting the votes in a recent Washington DC primary election needs some help. Given the recent problems with vote counting across the nation, he is concerned that the old system might cause controversy. As an expert programmer, you have been asked to help develop a new system that will correctly count the votes in a recent election, as well as providing some statistics about the election. Unfortunately, the person you are working for is very busy, and has only provided you with some raw data and told you what you are expected to program. It is your job to figure out a way to finish the tasks before the deadline next Thursday.