Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Similar documents
Programming Languages

Programming Languages

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Programming Languages

Programming Languages

Recap from last Python lecture

Recap from last Python lecture. Today: Revisit some objects. Update subsequence. What can sequences do? Update subsequence.

x = e Python tries to avoid overwrites i Python tries to avoid overwrites next Monday Programming Assignment #7 on Prolog quarter Assignment Revisited

CS558 Programming Languages

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS558 Programming Languages

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

CS558 Programming Languages

Syntax Errors; Static Semantics

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

The role of semantic analysis in a compiler

CS558 Programming Languages

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Python debugging and beautification

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Try and Error. Python debugging and beautification

Scope. Chapter Ten Modern Programming Languages 1

CSE 307: Principles of Programming Languages

CSE : Python Programming

Ruby: Introduction, Basics

CS558 Programming Languages

CS558 Programming Languages

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Variables and Bindings

Programming Languages

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Lecture 16: Static Semantics Overview 1

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

The Pyth Language. Administrivia

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

Programming Languages

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CS558 Programming Languages. Winter 2013 Lecture 3

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Back to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.

. p.1/23. Today. 1. Questions and discussion from lecture. 2. Type-checking Functions Arrays Records (maybe)

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Programming Languages

CMSC 330: Organization of Programming Languages

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

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

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Announcements for this Lecture

Python: Short Overview and Recap

Senthil Kumaran S

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

Key components of a lang. Deconstructing OCaml. In OCaml. Units of computation. In Java/Python. In OCaml. Units of computation.

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

Overview of Semantic Analysis. Lecture 9

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Programmiersprachen (Programming Languages)

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

CSCI B522 Lecture 11 Naming and Scope 8 Oct, 2009

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

PIC 16, Fall Variables, Dynamically-typed, Mutable, Immutable, Functions. Michael Andrews. October 1, Department of Mathematics UCLA

(CC)A-NC 2.5 by Randall Munroe Python

C++ Support Classes (Data and Variables)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Lecture 7: Data Abstractions

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

CS 101 Spring 2006 Final Exam Name: ID:

Module 09: Additional Options for Organizing Data

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types

Python and Bioinformatics. Pierre Parutto

Begin at the beginning

Recap: Functions as first-class values

CIS192 Python Programming

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Names, Scope, and Bindings

STA141C: Big Data & High Performance Statistical Computing

Programming Languages and Techniques (CIS120)

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

Programming Languages

Lecture Agenda. Objects. But First... Immutable Types and Nesting. Immutable Types and Nesting

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Ruby: Introduction, Basics

The Dynamic Typing Interlude

News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

Overloading, Type Classes, and Algebraic Datatypes

Transcription:

CSE 130 : Winter 2009 Programming Languages Lecture 11: What s in a Name? Today: Revisit some objects Exploit features and build powerful expressions Base: int, float, complex Sequence: string, tuple, list Maps (Dictionary): key value Key data structure: Dictionaries Associative arrays, Hash tables A table storing a set of keys, And a value for each key. Any (immutable) object can be a key! int,float,string,tuples Very useful! Using Dictionaries Unsorted list of key,value pairs Empty Dictionary: {} Non-empty Dictionary: {k1:v1,k2:v2, } Membership: is k in dict: k in d Lookup value of key: d[k] Set value of key: d[k]=v

Dictionaries d={} d=dict(mexmenu) d[ ceviche ] = 3.95 d { } d[ burrito ] 3.50 d.keys() d.values() Dictionaries def freq(s): d={} for c in s: if c in d: d[c]+=1 else: d[c]=1 return d def plotfreq(s): d=freq(s) for k in d.keys(): print k, * *d[k] d=plotfreq([1,1,3.0, A,3.0, A, A,1,2,3.0,1, A ]) d d = plotfreq( avrakedavra ) d.keys() d f = open( foo.txt, read ) f.readlines() for l in f.readlines(): <BODY> f.close You now know enough to do PA6 Python Tutorial: How to open files, read lines Use the help command Document every function: What does it do?

Next: What s in a name? More precisely: How should programmer think of data What does a variable x really mean? What s in a name? ML (or Functional Languages) Name refers to a Value Binding maps Names to Values Environment list of bindings Environment can be extended Environment can t be changed Data model in functional PL Vars = names in phonebook Evaluation = Most recent Environment frozen in function value behavior of function cannot be changed easier reasoning Data model in OO langs Variables point to objects Objects = boxes with data inside pumpkin Y 3.142 Z [1,2,3]

Namespaces Manage variable names in Python Ok, but what IS a namespace? A mapping from names to objects Similar to, but different from Environments Core PL concept, unifies many ideas pumpkin We will see very important differences Y 3.142 Z [1,2,3] Namespaces vs. Environments Both are maps from variables to something 1. Assignment Basic operation in Imperative PL: Namespace Environment x = e What s the difference? 1.Assignment 2.Updates/Mutation 1.Compute object corresponding to e 2.Change the name x to refer to object

Simple example i,s = 0,0 while (i <= 3): i,s = i+1, s+i 1. Assignment Basic operation in Imperative PL: x = e 1.Compute object corresponding to e 2.Change the name x to refer to object Same name s - points to different objects - namespace is not extended Assignment: changes box that name refers to 2. Update/Mutation Change what s inside the box (object) - Not with immutable objects - eg. integers - But with mutable objects - eg. tuples, arrays, lists, dictionaries Aliasing Two or more names refer to same object Peter Parker x = [100,200] x [100, 200] x[0] = "gobble gobble" x ['gobble gobble', 200] How is it different from build a new box with updated value inside? Spider-Man

Aliasing Two or more names refer to same object >> x = [100,200] >> y = x Y [100,200] Aliasing and Update Two or more names refer to same object >> x = [100,200] >> y = x Y >> y[0] = gobble gobble" >> x [ gobble,200] [100,200] Aliasing Two or more names refer to same object >> x = [100,200] >> y = x Y >> y[0] = gobble gobble" >> x [ gobble gobble,200] If multiple names refer to same object, update affects values of all names [ gobble,200] [100,200] Aliasing Does not happen in Ocaml/Functional PLs actually it does happen (where?) but not exposed to the (130) programmer Does happen in every imperative PL Java, Python: names point to objects C: names point to memory cells

Aliasing Good because? Namespaces everywhere Namespace = map from names to objects Notion of namespace pervades Python Bad because? Can create namespace, Can name a namespace, Can peep inside a namespace (see whats bound) Go to code! Creating Namespaces Namespaces a.py x = 22 y = this sentence is false 22 Y this a Y this a 22 pumpkins b.py x = pumpkin y = 3.142 pumpkin Y 3.142 b Y 3.142 b import a a.x 22 Different names can point to same object!

Namespaces For two namespaces a, b: names inside unrelated names in different spaces a.x : attribute/name x in space a b.x : attribute/name x in space a 22 Y Different names can point to same object! a this pumpkin Y 3.142 b Creating Namespaces: Fun Calls x = 10 def f(y): y = y + x return y f(x) Call-by-Value: 10 f <fun> y 20 f(x) globals New local namespace for call y bound to same object (value) as arg x x binding unchanged by call In this case, after call, local namespace disappears Creating Namespaces: Fun Calls Creating Namespaces: Fun Calls 2 x = 10 def f(y): y = y + x return y f(x) Questions: 10 f <fun> y 20 f(x) globals Why new local namespace (not just stack)? What s the deal with x not declared/bound in f? When do we need to freeze a namespace? y = 0 x = [10] def f(y): z = len(x)+y return z f(5) Static Scoping Lookup at runtime Not compile time Missing z added len <fun> y 0 x 20 f <fun> y 5 z 6 f(5) globals builtins

Creating Namespaces: Fun Calls 3 def g(y): return y + n g(5) NameError: global name 'n' is not defined What happened? Looks for n at run-time,when g is called Can t find n in local, global, builtins Throws run-time error Creating Namespaces: Fun Calls 3 def g(y): return y + n g(5) NameError n = 10 g(5) 15 What happened? Looks for n at run-time,when g is called Finds n in global, returns 15 Here n is a free variable of g Needs to be bound in some enclosing scope Aaargh! Python tries to avoid overwrites def g(y): def return g(y): y + n g(5) return y + n NameError g(5) NameError n = 10 n g(5) = 10 15 g(5) 15 n = 100 g(5) 105 Changed behavior after definition whether or not fun works depends on what we did after fundef Change I/O behavior too Unlike ML, no new binding: just change what n is bound to be careful with free variables! n 100 def f(): n = smash print n f() smash n 100 Python tries to ensure you don t overwrite outer variables

Python tries to avoid overwrites Python tries to avoid overwrites n 100 def f(): n = smash print n f() smash n 100 Python tries to ensure you don t overwrite outer variables How? - unlike C/Java - assignment different from reads - no variable declarations - assignment = declaration! Assignment Revisited x = e 1.Compute object corresponding to e 2.Change the name x to refer to object in the current namespace (added if missing) Python tries to avoid overwrites n 100 def f(): n = smash print n f() smash n 100 What happens? x = 10 def g(): x = x + 1 print x g() x

What happened? x = 10 def f(): x = x + 1 print x f() You may think it should print 11, and leave the global unchanged... but here is what really happens Since x is assigned in the function, it treats x as a local, and so it adds a binding for it. But then it looks up x for evaluating x+1, and it can t find a local x ERROR What happens? x = 10 def g(): global x x = x + 1 print x g() x What happens? x = [10] def g(): x[0] = abc print x g() x What happens? x = [10] def g(): x[0] = abc print x g() x

What happens? x = [10] def f(y): def h(z): return (y+x[0]+z) return h foo = f(5) foo <function object> foo(100) 115 foo1 = f(-5) foo1(100) 105