CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

CS61A Lecture 24 Infinite Sequences
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
Recursively Defined Functions
Data Abstraction… The truth comes out…. What we’re doing today… Abstraction ADT: Dotted Pair ADT: List Box and Pointer List Recursion Deep List Recursion.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
 1 String and Data Processing. Sequential Processing Processing each element in a sequence for e in [1,2,3,4]: print e for c in “hello”: print c for.
CSC 1701B Computing: Science and Creativity. Outline  Types  Variables  Operators  Control: sequence, selection, repetition  Functions (block headings.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
UC Berkeley EECS Sr Lecturer SOE Dan Garcia printing-aims-to-prevent-a-piracy-plague/ Quest.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 6 Recursion Tom Magrino and Jon Kotker UC Berkeley EECS June 26, 2012.
Constraint Satisfaction Problems (CSPs) CPSC 322 – CSP 1 Poole & Mackworth textbook: Sections § Lecturer: Alan Mackworth September 28, 2012.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
The role of data mining in the last presidential election. A mind-blowing piece on how the Obama campaign used various sources of data to target voters.
CS61A Lecture 30 MapReduce Jom Magrotker UC Berkeley EECS August 8, 2012 Slides developed from those of John DeNero, Paul Hilfinger, and Eric Tzeng.
Built-in Data Structures in Python An Introduction.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 3: Levels of Abstraction
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
Collections Michael Ernst CSE 190p University of Washington.
Understanding ADTs CSE 331 University of Washington.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
UC Berkeley EECS Sr Lecturer SOE Dan Garcia printing-aims-to-prevent-a-piracy-plague/ Quest.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.
UC Berkeley EECS Lecturer SOE Dan Garcia The success of Apple’s Siri (only available on the iPhone 4S) has sparked competition, to be sure. Google’s IRIS.
Section Recursion 2  Recursion – defining an object (or function, algorithm, etc.) in terms of itself.  Recursion can be used to define sequences.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
UC Berkeley EECS Sr Lecturer SOE Dan Garcia Valve (video game makers of Half-Life) believes the future of video games may not be in the input device (ala.
Fall 2002CMSC Discrete Structures1 Chapter 3 Sequences Mathematical Induction Recursion Recursion.
CMSC201 Computer Science I for Majors Lecture 23 – Algorithms and Analysis Prof. Katherine Gibson Based on slides from previous iterations.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Algorithmic complexity: Speed of algorithms
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Recursively Defined Functions
Mathematical Induction Recursion
6.001 SICP Data abstractions
Important Concepts from Clojure
Important Concepts from Clojure
The Metacircular Evaluator
CS190/295 Programming in Python for Life Sciences: Lecture 6
Recitation Outline C++ STL associative containers Examples
Advanced Algorithms Analysis and Design
Algorithmic complexity: Speed of algorithms
(more) Python.
Programming Languages
Lecture #7 מבוא מורחב.
For loops Taken from notes by Dr. Neil Moore
List and list operations (continue).
Important Concepts from Clojure
Today’s topics Abstractions Procedural Data
Algorithmic complexity: Speed of algorithms
Instructor: Dr. Michael Geiger Spring 2019 Lecture 34: Exam 3 Preview
Presentation transcript:

CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012

2 C OMPUTER S CIENCE IN THE N EWS Prototypes available to developers at the beginning of next year for around $1500 and to general public in Skydivers wore Glasses and jumped off a plane: their views were transmitted live to an audience at the Moscone Center. (Video: 8b2t3QE) 8b2t3QE Glasses are meant to interact with people’s senses, without blocking them. Display on the Glasses’ computer appears as a small rectangle on a rim above the right eye. Google unveils Glass at Google I/O, June 27

3 T ODAY Review: Tuples. Review: Data abstraction. New sequences and data structures: Ranges, Pairs, Immutable recursive lists.

4 S EQUENCES A sequence is an ordered collection of data values. There are many kinds of sequences, and all share certain properties. Length: A sequence has a finite length. Element selection: A sequence has an element for any non-negative integer less than its length.

5 R EVIEW : T UPLES A tuple is a built-in type that represents a sequence. >>> triplet = (1, 2, 3) >>> len(triplet) 3 >>> triplet[0] 1 >>> from operator import getitem >>> getitem(triplet, 0) 1 Tuples have length. Elements can be selected.

6 R EVIEW : T UPLES A tuple is an example of a data structure. A data structure is a type of data that exists primarily to hold other pieces of data in a specific way.

7 R EVIEW : W ORKING WITH T UPLES Write the higher order function map, which takes a function fn and a tuple of values vals, and returns a tuple of results of applying fn to each value in vals. >>> map(square, (1, 2, 3, 4, 5)) (1, 4, 9, 16, 25) >>> map(lambda x: x+1, (1, 2, 3, 4, 5)) (2, 3, 4, 5, 6)

8 R EVIEW : W ORKING WITH T UPLES Write the higher order function map, which takes a function fn and a tuple of values vals, and returns a tuple of results of applying fn to each value in vals. def map(fn, vals): results = () for val in vals: results = results + (fn(val),) return results Start with an empty tuple. Iterate over the elements of the tuple. Add the new element to the growing tuple.

9 R EVIEW : W ORKING WITH T UPLES Write the higher order function filter, which takes a predicate function pred and a tuple of values vals, and returns a tuple of values that satisfy the predicate. >>> filter(lambda x: x%2==0, (1, 2, 3, 4, 5)) (2, 4) >>> filter(isprime, (2, 3, 4, 5, 6)) (3, 5) Predicate functions return True or False.

10 R ANGES >>> range(0, 10) range(0, 10) >>> tuple(range(0, 10)) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >>> tuple(range(4)) (0, 1, 2, 3) >>> tuple(range(0, 4, 2)) (0, 2) >>> len(range(0, 10)) 10 >>> range(1, 10)[3] 4 >>> sum = 0 >>> for val in range(5):... sum += val >>> sum 10 >>> for _ in range(3):... print(“Go Bears!”) Go Bears! A range is another built-in type that represents a sequence. It represents a range of integers.

11 A NNOUNCEMENTS Homework 4 is due July 3. Homework 5 is released, due July 6. Project 2 is released, due July 13. No class on Wednesday, July 4. Project 1 contest is on! – How to submit: Submit a file with your final_strategy to proj1-contest. – Deadline: Friday, July 6 at 11:59pm. – Prize: One of 3 copies of Feynman and 1 extra credit point. – Metric: We will simulate your strategy against everyone else’s, and tally your win rate. Draws count as losses.

12 A NNOUNCEMENTS : M IDTERM 1 Midterm 1 is on July 9. – Where? 2050 VLSB. – When? 7PM to 9PM. – How much? Material covered until July 4. Closed book and closed electronic devices. One 8.5” x 11” ‘cheat sheet’ allowed. Group portion is 15 minutes long. Post-midterm potluck on Wednesday, July 11.

13 R EVIEW : D ATA A BSTRACTION We want to think about data in terms of its meaning, not its representation. Programs should operate on abstract data. We use functions to create a division between manipulation and representation. Functions can be constructors or selectors.

14 E XAMPLE : S TUDENT R ECORDS We would like to work with student records. make_student(name, id, grades) creates a new record. name(student) returns the name of student. calid(student) returns the ID of student. grades(student) returns a tuple of grades of student. C ONSTRUCTOR S ELECTORS

15 E XAMPLE : S TUDENT R ECORDS Write a function names_start_with that takes in a tuple of student records, records, and a letter, and returns a tuple of the IDs of the students whose name starts with letter.

16 E XAMPLE : S TUDENT R ECORDS Write a function names_start_with that takes in a tuple of student records, records, and a letter, and returns a tuple of the IDs of the students whose name starts with letter. def names_start_with(records, letter): results = () for record in records: if name(record).startswith(letter): results = results + (calid(record),) return results Did not even have to implement the functions for the student record abstract data type (ADT).

17 E XAMPLE : S TUDENT R ECORDS Can use anything to construct the student record, as long as the selectors are consistent. def make_student(name, id, grades): return (name, id, grades) def name(student): return student[0] def calid(student): return student[1] def grades(student): return student[2]

18 R ESPECT THE D ATA A BSTRACTION ! Louis Reasoner wrote the following code to count the number of As for a given student. However, he has a data abstraction violation. Correct his code so that it respects the data abstraction. def count_as(student): number_of_as = 0 for grade in student[2]: if grade == “A”: number_of_as = number_of_as + 1 return number_of_as

19 R ESPECT THE D ATA A BSTRACTION ! Louis Reasoner wrote the following code to count the number of As for a given student. However, he has a data abstraction violation. Correct his code so that it respects the data abstraction. def count_as(student): number_of_as = 0 for grade in grades(student): if grade == “A”: number_of_as = number_of_as + 1 return number_of_as

20 B REAK

21 I MMUTABILITY Numbers, Booleans, strings, tuples, and ranges are examples of immutable data structures. Values do not change over time.

22 I MMUTABILITY To “modify” an immutable data structure, we would need to make a brand new object with the new values. def map(fn, vals): results = () for val in vals: results = results + (fn(val),) return results Makes a new tuple!

23 D ATA S TRUCTURE : P AIRS A pair is an ADT that can hold two elements. It can be implemented using tuples. (But it can be implemented in other ways, including using functions.) make_pair(x, y) creates a new pair. first(x) returns the first element of the pair. second(x) returns the second element of the pair. C ONSTRUCTOR S ELECTORS

24 N ESTED P AIRS For simplicity, we will represent pairs as two- element tuples. Pairs can contain other pairs as elements. (1, 2) ((1, 2), 3) ((1, 2), (3, 4)) ((1, (2, 3)), 4)

25 N ESTED P AIRS : B OX - AND -P OINTER D IAGRAM (1, 2) 12 The box represents the pair. This arrow shows the start of the pair. First element Second element

26 N ESTED P AIRS : B OX - AND -P OINTER D IAGRAM ((1, 2), 3) 3 12 First element of the outer pair Second element of the outer pair

27 N ESTED P AIRS : B OX - AND -P OINTER D IAGRAM ((1, 2), (3, 4)) 1234

28 N ESTED P AIRS : B OX - AND -P OINTER D IAGRAM Draw the box-and-pointer diagrams for the following pairs: (1, (2, 3)) ((1, (2, 3)), 4) (1, (2, (3, 4)))

29 N ESTED P AIRS : B OX - AND -P OINTER D IAGRAM Nested pair (1, (2, (3, ())))) 1 23 Empty tuple

30 N EW D ATA S TRUCTURE Immutable Recursive List One possible (and useful) representation of a list with elements 1, 2 and

31 I MMUTABLE R ECURSIVE L ISTS An immutable recursive list (or an IRList) is a pair such that: The first element of the pair is the first element of the list. The second element of the pair is the rest of the list – another immutable recursive list. The rest of the list could be empty. Definition is recursive!

32 I MMUTABLE R ECURSIVE L ISTS 1 23 An IRList is a pair. The first element of the pair is the first element of the list. The second element of the pair is the rest of the list. The empty tuple represents the empty list, and the end of the list. Also an IRList!

33 I MMUTABLE R ECURSIVE L ISTS empty_irlist = () def make_irlist(first, rest=empty_irlist): return (first, rest) def irlist_first(irlist): return irlist[0] def irlist_rest(irlist): return irlist[1] C ONSTRUCTOR S ELECTORS

34 I MMUTABLE R ECURSIVE L ISTS make_irlist(1, make_irlist(2, make_irlist(3, empty_irlist))) 1 23

35 I MMUTABLE R ECURSIVE L ISTS Why are they useful? They are defined recursively. Functions that operate on IRLists are usually best and easily defined recursively. They are the basis for linked lists, a versatile data structure in computer science.

36 I MMUTABLE R ECURSIVE L ISTS Write the function irlist_len that takes an IRList irlist and returns its length. def irlist_len(irlist): if irlist == empty_irlist: return 0 return 1 + irlist_len(irlist_rest(irlist)) Base case: Simplest IRList is the empty IRList. Add 1 to the result of calling irlist_len recursively on the rest of the IRList, which is also an IRList.

37 I MMUTABLE R ECURSIVE L ISTS 1 23 irlist_len 23 = 1 + irlist_len 3 = irlist_len= irlist_len

38 I MMUTABLE R ECURSIVE L ISTS 1 23 irlist_len 23 = 1 + irlist_len 3 = irlist_len= irlist_len Z ERO

39 I MMUTABLE R ECURSIVE L ISTS Write the function irlist_select that returns the element at position index of the irlist. (Assume the inputs are valid.) def irlist_select(irlist, index): if index == 0: return ______________________ return irlist_select(____________, ____________)

40 I MMUTABLE R ECURSIVE L ISTS Write the function irlist_select that returns the element at position index of the irlist. (Assume the inputs are valid.) def irlist_select(irlist, index): if index == 0: return irlist_first(irlist) return irlist_select(irlist_rest(irlist), index - 1)

41 I MMUTABLE R ECURSIVE L ISTS Write the function irlist_map that takes a function fn and an irlist, and returns an IRList of the results of applying fn to the elements of irlist. def irlist_map(fn, irlist): if irlist == empty_irlist: return _______________________________ return make_irlist(_______________________, _______________________) IRLists are immutable!

42 I MMUTABLE R ECURSIVE L ISTS Write the function irlist_map that takes a function fn and an irlist, and returns an IRList of the results of applying fn to the elements of irlist. def irlist_map(fn, irlist): if irlist == empty_irlist: return empty_irlist return make_irlist(fn(irlist_first(irlist)), irlist_map(fn, irlist_rest(irlist)) IRLists are immutable!

43 C ONCLUSION Data abstraction allows us to separate the meaning of abstract data from its implementation. A sequence is an ordered collection of data with certain properties. There are many useful ADTs in computer science, some of which are immutable. One example of a useful ADT is the immutable recursive list, built from pairs. Preview: Immutable dictionaries.