dynamic languages - cs.rpi.edumilanova/csci4430/lecture25.pdfdynamic languages read: scott, chapter...
TRANSCRIPT
-
1
Dynamic Languages
Read: Scott, Chapter 14 (optional)
-
2
Lecture Outline
n Scripting programming languages
n Dynamic programming languages
n Taking stock: PL design choices
n Python
Programming Languages CSCI 4430, A. Milanova
-
3
Scripting Languages
n E.g., Tcl, awkn Originate in the 1970’s from UNIX (shell scripts)
n Purposen To process text files with easen To launch components and combine (or “glue”) these
components into an applicationn Characteristics
n Ease of use, flexibility, rapid prototyping: hence, scripting languages are dynamically typed
n Extensive support for text processingProgramming Languages CSCI 4430, A. Milanova
-
References
n Following slides are based on n “The Rise of Dynamic Languages” talk by Jan
Vitekn “The Essence of JavaScript”, ECOOP’10 paper
by Shriram Krishnamurthi et al. n “The Eval that Men Do”, ECOOP’11 paper by
Gregor Richards et al.
Programming Languages CSCI 4430, A. Milanova 4
-
2 Decades of Dynamic Languagesn Visual Basic dyn 1991n Python dyn 1991n Lua dyn 1993n R dyn 1993n Java stat+dyn 1995n JavaScript dyn 1995n Ruby dyn 1995n PHP dyn 1995
Programming Languages CSCI 4430, A. Milanova 5
n C# stat+dyn 2001n Scala stat 2002n F# stat 2003n Clojure dyn 2007n Julia dyn 2009
Last decade or so:n Go stat ~2009n Rust stat 2010n Swift stat 2014n TypeScript stat+dyn
-
6
2011: 2013:
-
Characteristics
n Dynamic typing, also known as Duck typingn Type checking amounts to running the “Duck
test” at runtime:“If it walks like a duck and swims like a duck and
quacks like a duck, then it is a duck.” ---paraphrased from J. W. Riley
fun F( x ) {x.quack();
}Programming Languages CSCI 4430, A. Milanova 7
-
Other Characteristics
n Reference model, garbage collectedn Reflective! (i.e., eval is a prominent feature)
n Use of eval ranges “from sensible to stupid” (ref. “The Eval that Men Do” by Richards et al.)
eval is evil. Avoid it.eval has aliases. Don’t use them.
--- Douglas Crockford
8Programming Languages CSCI 4430, A. Milanova
-
Other Characteristics
n Use of eval ranges “from sensible to stupid” (ref. “The Eval that Men Do” by Richards et al.)
var flashVersion = parse();
flash2Installed = flashVersion == 2;flash3Installed = flashVersion == 3;… // same for versions 4 to 11for (var i = 2; i
-
The Eval that Men Do
Programming Languages CSCI 4430, A. Milanova 10
-
The Eval That Men Do
Programming Languages CSCI 4430, A. Milanova 11
-
Other Characteristics
n High-level data structures, libraries n Lightweight syntaxn Delay error reporting, error-oblivious
n Very difficult to trace and fix errors
n Performance challengedn C interpreters ~2-5 times slower than Javan Java interpreters ~16-43 times slower than Java
12Programming Languages CSCI 4430, A. Milanova
-
A bit on JavaScript
n 95% of all web sites use JavaScript
n Single-threadedn Reference model, garbage collectedn Reflective! (i.e., eval is a prominent feature)n High-level data structures, libraries n Lightweight syntaxn Error-oblivious
Programming Languages CSCI 4430, A. Milanova 13
-
Objects and Fields in JavaScript
n Objects have fields (field are also known as properties)
n Field lookupn x[“f”], x.fn { “f” : 7 }[“g”]
JavaScript is error-oblivious, in the above example, it returns undefined, and continues!
n Field updaten x[“f”] = 2, x.f = 2n { “f” : 0 }[“g”] = 10 results in{ “f” : 0, “g” : 10 } 14
-
Objects and Fields in JavaScript
n Field deleten delete x.fn delete { “f” : 7, “g” : 0 }[“g”]
Programming Languages CSCI 4430, A. Milanova 15
-
Arrays Are Objectsfunction sum(arr){ var r = 0;for (var i=0; i
-
Functions Are Objects
f = function(x) { return x+1 }f.y = 90f(f.y) yields what?
Other unexpected behavior… with statementeval
17
-
Wat?
n https://www.destroyallsoftware.com/talks/wat
Programming Languages CSCI 4430, A. Milanova 18
-
19
Lecture Outline
n Scripting programming languages
n Dynamic programming languages
n Taking stock: PL design choices
n Python
Programming Languages CSCI 4430, A. Milanova
-
20
Taking Stock: Design Choices
Scheme Booleans, Numbers,Symbols,Lists
Conditional flow,Recursion
Reduction/Function application
Java Primitive types,Classes (library, and user-defined)
Conditional flow,Iteration
State-transition/Assignment statement
C++ Primitive types,struct types, pointer types,array types,Classes
Conditional flow,Iteration
State-transition/Assignment statement
Datatypes Control-flowSemantics/Basic Operation
Programming Languages CSCI 4430, A. Milanova
-
21
Taking Stock: Design Choices
Haskell ADTs, Type Classes
Conditional flow,Recursion
Reduction/Function application
Python
Datatypes Control-flowSemantics/Basic Operation
Programming Languages CSCI 4430, A. Milanova
-
Programming Languages CSCI 4430, A. Milanova 22
Taking Stock: Design Choices
Scheme
Java
C++
Variable ModelParameter
PassingMechanism
Scoping Typing
Referencemodel
Value model for simple types,reference model for class types
Value model
By value
By sharing
By value and by reference
Static, nested function definitions
Static
Static
Dynamic,type-safe
Static and dynamic,type-safe
Static,type-unsafe
-
Programming Languages CSCI 4430, A. Milanova 23
Taking Stock: Design Choices
Haskell
Python
Variable ModelParameter
PassingMechanism
Scoping Typing
Referencemodel
By name (lazyevaluation)
Static, nested function definitions
Static,type-safe
-
Programming Languages CSCI 4430, A. Milanova 24
Python
n Designed by Guido van Rossum at CWI Amsterdam in 1991
n Multi-paradigm programming languagen All characteristics of dynamic languagesn It has “functional” features
n E.g. higher-order functions, map and reduce on lists, list comprehensions
n It has “object-oriented” featuresn E.g., iterators, array slicing operations, reflection,
exceptions, (multiple) inheritance, dynamic loading
-
Programming Languages CSCI 4430, A. Milanova 25
Python: Syntax and Scoping
m=1; j=3 def outer():
def middle(k):def inner():m=4 # new local mprint (m,j,k)
inner()return m,j,k # 3 element tuple
m=2; # new local mreturn middle(j) # old (global) j
print (outer())print (m,j)
Scott Variable belongs to block where it is written, unless explicitly imported.What is the output of this program?
-
Programming Languages CSCI 4430, A. Milanova 26
Python: Syntax and Scoping
m=1; j=3 def outer():
def middle(k):def inner():global m # from main program, not outerm=4print (m,j,k)
inner()return m,j,k # 3 element tuple
m=2; # new local mreturn middle(j) # old (global) j
print (outer())print (m,j)
Scott Variable belongs to block where it is written, unless explicitly imported.What is the output of this program?
What’s printed if we removedthe red “global m” statement? then remove the blue assignment?
-
Programming Languages CSCI 4430, A. Milanova 27
Python: Syntax and Scoping
m=1;def outer():
def middle():def inner():return m;
inner()return inner # middle returns a closure
m=2 # { inner() { return m; }, m->2 } return middle()
fun = outer() # fun is a reference to closureprint (fun())
What is the output of this program?
-
Programming Languages CSCI 4430, A. Milanova 28
Scoping: Static Scoping Rules
n Blocks (scopes) are defined by indentationn There are no variable declarations
n A variable belongs to block where it is writtenn “Closest enclosing scope” rule applies
n Lookup proceeds from inner to outer blocksn ‘global’ overrides rule for access to outermost
scopen Functions are first class values
n Static scoping entails closures and unlimited extent
-
Programming Languages CSCI 4430, A. Milanova 29
Datatypes
n Numbers (+, *, **, pow, etc) - immutablen Collections
n Sequencesn Strings are immutable!n Listsn Tuples are immutable!
n Mappingsn Dictionaries
n Files
-
Programming Languages CSCI 4430, A. Milanova 30
Datatypesn So, what model for variables does Python use?
n Reference model for variables
n Equalityn == equal in value (structural equality, value equality)
(Same in Scala, == redirects to equals!)n is same object (reference equality)n None acts like null in C, a placeholder for an actual value
-
31
Control Flown Short-circuit evaluation of boolean
expressions n Constructs for conditional control flow and
iteration: if, while, forfor x in [“spam”, “eggs”, “ham”]:
print x #iterates over list elementss = “lumberjack”for y in s: print y #iterates over chars
n Use of iterators defines the “Python style”Programming Languages CSCI 4430, A. Milanova
-
32
Functionsn Two forms of function definition. First class values
def incr(x): return x+1 #function incr#list of 2 functionsincrs = [lambda x: x+1, lambda x: x+2]
n Polymorphism#what datatypes can this function be used on?def intersect(seq1, seq2):res = [ ]for x in seq1: #iterates over elements in seq1if x in seq2: #checks if element is in seq2res.append(x) #if so, adds element to list
return res
print intersect([1,2,3],[2,4,6]) #[2]print intersect( (1,2,3,4), (4,3,5)) #[3,4]print intersect( (1,2,3), [1,2,3]) #[1, 2, 3]print intersect({1:'a',2:'b',3:'c'}, {1:'a',4:'d'}) #[1]print intersect({1:'a',2:'b',3:'c'}, {4:'a',5:'b'}) #[]#clearly the intersection is on the keys, not the values!
-
Programming Languages CSCI 4430, A. Milanova 33
Functionsn What is the parameter passing mechanism in
Python?
n Call by valuen But each value is a reference! n So we say that parameter passing is call by sharingn Be careful: if we pass a reference to a mutable object,
callee may change argument object
-
Taking Stock: Python
n Datatypes?n Control flow?n Basic operation?n Variable model?n Parameter passing mechanism?n Scoping?
n Are functions first-class values?n Typing?
Programming Languages CSCI 4430, A. Milanova 34