PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley

Similar documents
Intro. Scheme Basics. scm> 5 5. scm>

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Discussion 4. Data Abstraction and Sequences

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

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

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

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))

CS61A Notes Week 9: Muta4on (solu4ons) Revenge of the Box- and- pointers

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

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CSE413 Midterm. Question Max Points Total 100


CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Remember, this question was mis-worded: you could also add quoted words and sentences in the blanks below. This allowed for a solution to [4] below.

Scheme Basics > (butfirst '(help!)) ()

Warm-up! CS 3 Final Review. Predict the output. Predict the Output. Predict the output. Predict the output. What is your favorite color?

SCHEME AND CALCULATOR 5b

Write a procedure powerset which takes as its only argument a set S and returns the powerset of S.

Sample midterm 1 #1. Problem 1 (What will Scheme print?).

XP: Backup Your Important Files for Safety

Have the students look at the editor on their computers. Refer to overhead projector as necessary.

Part I Introduction: Functions

CS450 - Structure of Higher Level Languages

Programming Languages. Thunks, Laziness, Streams, Memoization. Adapted from Dan Grossman s PL class, U. of Washington

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

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

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

A Brief Introduction to Scheme (II)

CS 3 Midterm 1 Review

UNIVERSITY of CALIFORNIA at Berkeley Department of Electrical Engineering and Computer Sciences Computer Sciences Division

User-defined Functions. Conditional Expressions in Scheme

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

CSCI 3155: Principles of Programming Languages Exam preparation #1 2007

6.001 Notes: Section 17.5

CS3 Midterm 1 Fall 2006

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

CS3L Summer 2011 Exam 2 Time: up to 170 minutes (you may leave when finished; or, you must stop promptly at noon)

Recursive Data and Recursive Functions

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

We learned in Chapter 20 how to read from the keyboard and write to the screen. The

CS3: Introduction to Symbolic Programming. Lecture 14: Lists Scheme vs. other programming languages.

Homework 1. Reading. Problems. Handout 3 CSCI 334: Spring, 2012

Discussion 11. Streams

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

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

Read and fill in this page now. Your lab section day and time: Name of the person sitting to your left: Name of the person sitting to your right:

1. The Square limit language

5Data. 5.1 Types. scalar

Department of Electrical Engineering and Computer Sciences Spring 2001 Instructor: Dan Garcia CS 3 Midterm #2. Personal Information

CS3: Introduction to Symbolic Programming. Lecture 14: Lists.

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

1.7 Limit of a Function

CS61A, Fall/1999 Midterm #1 Professor Brian Harvey

Department of Electrical Engineering and Computer Sciences Fall 2000 Instructor: Dan Garcia CS 3 Final Exam

Drawing Hands, by M. C. Escher (lithograph, 1948)

For this chapter, switch languages in DrRacket to Advanced Student Language.

6.001 Notes: Section 8.1

Functions that return lists

Lisp. Versions of LISP

This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

Putting the fun in functional programming

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

CS 61A Midterm #2 ver March 2, 1998 Exam version: A. Your name. login: cs61a- Discussion section number. TA's name

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

CS 275 Name Final Exam Solutions December 16, 2016

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

6.001 Notes: Section 5.1

5Data. 5.1 Types. scalar. datatype

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Representing Images as Lists of Spots

Modern Programming Languages. Lecture LISP Programming Language An Introduction

2.2 Hierarchical Data and the Closure Property

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

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

CS 61A Midterm #2 - October 5, 1998

12 Macros. Localmake. is an abbreviation for the two instructions. localmake "fred 87. local "fred make "fred 87

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

16. Linked Structures and Miscellaneous

Functional Programming. Pure Functional Languages

Lists of Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 5.3

Functional Programming. Pure Functional Programming

OrbBasic Lesson 1 Goto and Variables: Student Guide

Introduction to Scheme

Exercise 6 - Addressing a Message

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

PROFESSOR: Well, now that we've given you some power to make independent local state and to model objects,

1 Parsing (25 pts, 5 each)

More About Recursive Data Types

OrbBasic 1: Student Guide

Lecture 19: Signatures, Structures, and Type Abstraction

by the evening of Tuesday, Feb 6

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Adding Machine Run 2

CS 4349 Lecture October 18th, 2017

Case Study: Undefined Variables

COPYRIGHTED MATERIAL. An Introduction to Computers That Will Actually Help You in Life. Chapter 1. Memory: Not Exactly 0s and 1s. Memory Organization

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

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

ASCII Art. Introduction: Python

Transcription:

PAIRS AND LISTS 6 GEORGE WANG gswang.cs61a@gmail.com Department of Electrical Engineering and Computer Sciences University of California, Berkeley June 29, 2010 1 Pairs 1.1 Overview To represent data types that have component parts (like the rank and suit of a card), you have to have some way to aggregate information. Many languages have the idea of an array that groups some number of elements. In Lisp the most basic aggregation unit is the PAIR two things combined to form a bigger thing. If you want more than two parts you can hook a bunch of pairs together. We ll discuss this more later. The constructor for pairs is cons; the selectors are car and cdr. PAIR CAR CDR The book uses pairs to represent many different abstract data types: rational numbers (numerator and denominator), complex numbers (real and imaginary parts), points (x and y coordinates), intervals (low and high bounds), and line segments (two endpoints). 1

rational interval numerator denominator low high complex point real imaginary x y segment segment point1 point2 x y x y Notice that in the case of line segments we think of the representation as one pair containing two points, not as three pairs containing four numbers. That s what it means to respect a data abstraction. 1.2 Exercise: cons Construct the following diagram using cons. 2 4 6 3 5 1.3 Naming So why the heck is it called car and cdr? Well, turns out that a long time ago, one of the earliest machines, the IBM 704, the machine to implement them had a memory which contained something called a address register and a decrement register. Therefore, car stands for the Contents of Address Register, and cdr stands for Contents of Decrement Register. But there s a very useful reason to using things like this, and it s used when we are going to combine our pairs into bigger pairs. The important thing is that we can combine car and cdr in a useful way, such that we get something like caddar which is the (car (cdr (cdr (car...)))) of something. How do you pronounce that out? Well, load ~cs61a/lib/prounounce.scm, and it will tell you. This is the most important part of Scheme! If you want to be a lisp wizard, you have to be able to say it right. 1.4 Exercise: Pair Accessors Explain that if a points to the upper left of the diagram above, how to extract each of the different numbers. 2

2 Sequences: Lists List Operations cons, append, list, car, cdr Well, building things like this is rather dull. What if we want to represent a sequence of things? We may want to use a data structure called a list. Although these typically contain data that is very similar, they don t have to be. You are used to sequential data structures in the form of sentences, and these are essentially the same thing. However, these have a few more bits of power. 1. They can contain other lists. 2. They can contain Procedures. 3. They can contain anything. And they are elegantly defined. They are recursively defined: A list is a pair whose cdr is a list. An empty list is a list. 2.1 Implementation Let s look at their implementation, before moving on to the selectors and constructors. The basic implementation is straightforward. It s using the pairs we re used to. Essentially, you just connect together a bunch of pairs together via the cdr, and at the very end, affix an empty list. Typically, in a flat list, the car contains all the information, while the cdr is another list. This is analogous to first and butfirst. 2.2 Selectors It s just car and cdr. The reason for this is that a list is just a pair. (Note, the converse is not true, a pair is not necessarily a list.) Therefore, when we re manipulating a list, it s possible to think about it as we re merely manipulating the first pair. 2.3 Constructors 2.3.1 cons This is the simple one. We know that we can make a pair with cons, so if we want to add an element to the beginning of a list, we just use cons. > (cons the (quick brown fox jumps over the lazy dog)) (the quick brown fox jumps over the lazy dog) The one thing we want to be careful about is that we must remember that cons is not unique to lists. Therefore, if we cons together a list and a list, we do not get a flat list, we get a deep list, as follows. Note that we will study deep lists in detail later this week. > (cons (the) (quick brown fox jumps over the lazy dog)) ((the) quick brown fox jumps over the lazy dog) 3

This turns out to be the most useful one, because most of the time when we re doing a recursive transformation, we re building a list one pair at a time. Let s look at map, the list analogy to every. (define (map fn seq) (if (null? seq) () (CONS (fn (car seq)) (map fn (cdr seq))))) 2.3.2 append This procedure takes two lists as its argument and returns a new list that is a copy of the old one with the last pair pointing to the new list. One student described this to me as basically writing them next to each other and then just erasing the two parens in between them. We will only deal with this procedure as being applied to two lists. > (append (the quick brown fox) (jumps over the lazy dog)) (the quick brown fox jumps over the lazy dog) It s most useful when combining results from multiple recursive calls, each of which returns a subset of the overall answer; you want to take the union of those sets, and that s what append does. 2.3.3 list This is the easiest to understand, but unfortunately, also the easiest to get wrong. In short, it creates spine pairs and points one of them to each of the arguments. For example: > (list (a list) word 87 #4 +) ((a list) word 87 #t +) In practice it turns out to not be very useful, because you can only really use it when you know exactly how many things you want in a list. A lot of list programming deals with sequences of arbitary length. Thus, list is useful when you use a fixed-length list to represent an abstract data type, such as a point in three-dimensional space: (define (point x y z) (list x y z)) 2.4 Exercises: Naming Come up with better names: (define (mystery x) (if (equal? x ()) #t (if (not (pair? x)) #f (mystery (cdr x))))) (define (mystery x y) (if (null? x) 4

y (cons (car x) (mystery (cdr x) y)))) 3 Lists vs. Sentences We started out the semester using an abstract data type called sentence that looks a lot like a list. What s the difference, and why did we do it that way? Our goal was to allow you to create aggregates of words without having to think about the structure of their internal representation (i.e., about pairs). We do this by deciding that the elements of a sentence must be words (not sublists), and enforcing that by giving you the constructor sentence that creates only sentences. Here s a slightly simplified version of sentences given what you now know about lists: ;;;;; In file cs61a/lectures/2.2/sentence.scm (define (se a b) (cond ((word? a) (se (list a) b)) ((word? b) (se a (list b))) (else (append a b)) )) (define (word? x) (or (symbol? x) (number? x)) ) The point is this. Se is a lot like append, except that the latter behaves oddly if given words as arguments. Se can accept words or sentences as arguments. Se always returns a flat list, but lists accept inputs that are not flat. 3.1 Example: Reverse Say you want to reverse a list. You ll see that this is a little tricky using cons, car, and cdr as the problem asks, but it s easy for sentences: (define (reverse sent) (if (empty? sent) () (se (reverse (bf sent)) (first sent)) )) 4 Box and Pointer Diagrams Here are a few things that students often get wrong: 1. An arrow can t point to half of a pair. Remember, the pair is essentially a data structure telling you where to find two pieces of information. It doesn t make sense to point to a a single half of a box, because that s like a mailing address pointing to another envelope. Thus, if you see something like (define x (car y)) where y is a pair, the arrow for x should point to the thing that the car of y points to, not to the left half of the y rectangle. 2. The direction of arrows (up, down, left, right) is irrelevant. You can draw them however you want to make the arrangement of pairs neat. That s why it s crucial not to forget the arrowheads! 5

3. There must be a top-level arrow to show where the structure you re representing begins. How do you draw a diagram for a complicated list? Take this example: ((a b) c (d (e f))) You begin by asking yourself how many elements the list has. In this case it has three elements: first (a b), then c, then the rest. Therefore you should draw a three-pair backbone: three pairs with the cdr of one pointing to the next one. (The final cdr is null.) Only after you ve drawn the backbone should you worry about making the cars of your three pair point to the three elements of the top-level list. 6