programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf ·...

29
Programming language design and analysis Mihai Oaida 15 December 2010

Upload: others

Post on 20-May-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Programming language design and analysis

Mihai Oaida

15 December 2010

Page 2: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Agenda

● Background

● Data and Control structures , Syntax

● Procedural Python

● OOP

● Under the hood

● Functional Python

● Decorators

● Concurrency

● Who is using it?

Mihai Oaida 1

Page 3: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Background

● invented by Guido Van Rossum in 1989

● Based on ABC ● Focus on clear syntax● Nesting by indentation● Infinite lists and numbers

● Current 2.7 and 3.1 ( backwards incompatible )

Mihai Oaida 2

Page 4: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Philosophy

● ABC was used to teach programming

● basic constructs and grammar to describe what you want to do

● code that is as understandable as plain English

  if "L" in "Linux":print "Hello World"

Mihai Oaida 3

Page 5: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Implementations

● cPython – the original one● Pypy – python in python ● Jython – for the JVM● IronPython - .NET integration● Tinypy – 64k of code

Mihai Oaida 4

Page 6: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Simple types

>>> a = 200

>>> b = 2**0.5 # square root

>>> x = 3+4j

>>> name = "mihai"

>>> name = u"mi\u021b\u0103"

>>> print name

mi ăț

>>>

Mihai Oaida 5

Page 7: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Iterable types

>>> tuple = (1,2,3) #immutable

>>> print tuple

(1, 2, 3)

>>> list = [1,2,3]

>>> list.append(4)

>>> list[2:]+list[:2]

[3, 4, 1, 2]

>>len(list) #can use sum,max,min

4

>>> get = {"page":"new","id":3}

Mihai Oaida 6

Page 8: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Tricks

Mihai Oaida 7

print "Hi"*20

a,b=b,a

print "Linux"[1:­1]

newName = name[:]

#in operator can be used for iterables1 in range(10) # True

Page 9: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Control structures

● Also has: elif, while● Does not have: switch

Mihai Oaida 8

for number in range(1000):    if number%5 == 0 and number%11 == 0:        print number

Page 10: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Functions - definition

Mihai Oaida 9

def fact(n):    if n ==0 :         return 1    else:         return n*fact(n­1)            print fact(5)

Page 11: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Functions – reference passing

Mihai Oaida 10

def compute(list,int):    list.append(4)    Int = 43

a_list=[1,2,3]

a_int = 3

compute(a_list,a_int)

print a_list # [1, 2, 3, 4]print a_int  # 3

Page 12: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Functions – named arguments

Mihai Oaida 11

def print_info(name,age,height=183):    "keyword arguments and default arguments"    print "%s is %d years old and %s cm tall"%(name,age,height)    print_info(name= "John",age=23)

print print_info.__doc__

Page 13: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Functions – variable-length arguments

Mihai Oaida 12

def multi_add(*vartuple):    "variable­length arguments"    return sum(vartuple)

print multi_add(1,2,3,4)

Page 14: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

OOP

Mihai Oaida 13

Multiple inheritanceNo public, private, protectedConventions are usedNo interfacesNo overloadingMethods are virtual

this is self, and not reserved

Objects can be modified at runtimeadd membersadd methods

Page 15: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

OOP - instance

Mihai Oaida 14

class Person():    name = None    age = None

    def __init__(self,name,age):        self.name = name        self.age = age    def show(self):        print self.name,self.age

me = Person("Mihai",24)me.show()

Page 16: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

OOP – Multiple inheritance

Mihai Oaida 15

class Kid(Mom,Dad):    def cutTimber(self):        Dad.cutTimber(self)        #cut timber

    def cook(self):        if "cook" in dir(Dad):            Dad.cook(self)        else:            Mom.cook(self)

Page 17: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

OOP – setters and getters

Mihai Oaida 16

class D():    x = None    y = None    privates = ["x","privates"]     def __setattr__(self, name, val):        if name not in self.privates:            self.__dict__[name] = val        else:            raise Exception("%s is read only" % (name))

Page 18: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

OOP - Exceptions

Mihai Oaida 17

a=2try:   a=a*b except NameError,e:    print e#name 'b' is not defined

try:    print 10/0except ZeroDivisionError,e:    print efinally:     print "Execute anyway"

Page 19: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Modules

● Like modula-3● Modules are files, with a separate namespace

Mihai Oaida 18

#import moduleimport mathprint math.pi

#import into current global namespacefrom math import *print pi

Page 20: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Under the hood

● assignments creates references ● for mutable objects use copy.copy● dynamic typing, but when declared types are

enforced● duck typing● objects have types● integer vs float division● type,isinstance , and __class__

Mihai Oaida 19

Page 21: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Under the hood

● .pyc files – fast loading● garbage collector

● reference counting● reference cycles

● JIT – pysco, pypy

Mihai Oaida 20

Page 22: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Functional programming

Mihai Oaida 21

lambda x:x+1

print (lambda x,y:x**y)(2,10)#1024

print map(lambda a: a*a, [1,2,3,4,5])#[1, 4, 9, 16, 25]

numbers = [1,2,3,4,5]numbers_under_4 = filter(lambda x: x < 4, numbers)print numbers_under_4#[1, 2, 3]

numbers = [1,2,3,4,5]print reduce(lambda a,b: a*b, numbers)#120

Page 23: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

List comprehension

● From Haskell● Lists to generate lists● Combine the power of for, if and lists in one line

Mihai Oaida 22

[x for x in range(1000) if x%5 ==0 and x%11==0]

sum([int(x) for x in str(2**1000)])

Page 24: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Generators

● For creating iterators

Mihai Oaida 23

def double(list):    for i in list:        yield i        yield i        for nr in  double(range(10)):    print nr   

Page 25: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Generators

● Yield saves state

Mihai Oaida 24

def fib():    p,q = 0,1

    while True:        p,q=q,p+q        yield p        seq = fib()for i in range(10):print seq.next()

Page 26: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Decorators

● Functions that transform functions

Mihai Oaida 25

def inc(func):    return lambda x:x+1

@incdef example(a):    return a

print example(41)#42 

print inc(example)(41)#42   

Page 27: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Concurrency

● Threads● cPython has a GIL ● Jython and ironPython do not

● Processes● CSP – using decorators

Mihai Oaida 26

Page 28: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Who is using it?

● YouTube, Google, NASA , Linux, Bit torrent● Used to teach programming● Has influenced Cobra and Ocaml(twt) on

nesting and syntax● EcmaScript with iterators, generators and list

comprehensions● Go, Groovy, Boo with philosophy

Mihai Oaida 27

Page 29: Programming language design and analysisstaff.cs.upt.ro/~marius/curs/plda/2011/old/lect11.pdf · Philosophy ABC was used to teach programming basic constructs and grammar to describe

Questions?