SlideShare a Scribd company logo
1 of 36
Class 32:
                   Interpreters



cs1120 Fall 2011
David Evans
7 November 2011
Plan
Implementing Interpreters
History of Object-Oriented Programming




 Problem Set 7: posted today, due Monday 14 November.
 • Understand the Charme interpreter (described in Chapter 11)
 • Modify it to change the evaluation rules


                                                                 2
Building a Language
Design the grammar
  What strings are in the language?
  Use BNF to describe all the strings in the language
Make up the evaluation rules
  Describe what every string in the language means
Build an evaluator
  Implement a procedure that takes a string in the
  language as input and an environment and outputs its
  value:
      meval: String Environment → Value
Is this an exaggeration?
It is no exaggeration to regard this
as the most fundamental idea in
programming:
  The evaluator, which determines
  the meaning of expressions in the
  programming language, is just
  another program.
To appreciate this point is to change
our images of ourselves as
programmers. We come to see
ourselves as designers of                       Abelson and
languages, rather than only users of      Sussman, Structure and
languages designed by others.           Interpretation of Computer
                                             Programs (p. 360)
Building an Evaluator
To build an evaluator we need to:
  Figure out how to represent data in programs
     What is a procedure, frame, environment, etc.
  Implement the evaluation rules
     For each evaluation rule, define a procedure that
     follows the behavior of that rule.

 Next: we’ll look at a high-level how the application rule is implemented
 Wednesday and Chapter 11: detailed walk-through of the interpreter
Core of the Evaluator




                        6
def meval(expr, env):
  if isPrimitive(expr):     return evalPrimitive(expr)
  elif isIf(expr):          return evalIf(expr, env)
  elif isDefinition(expr): evalDefinition(expr, env)
  elif isName(expr):        return evalName(expr, env)
  elif isLambda(expr):      return evalLambda(expr, env)
  elif isApplication(expr): return evalApplication(expr, env)
  else:
     error ('Unknown expression type: ' + str(expr))
Stateful Application Rule
To apply a constructed procedure:
1. Construct a new environment, whose parent is the
   environment of the applied procedure.
2. For each procedure parameter, create a place in the frame
   of the new environment with the name of the parameter.
   Evaluate each operand expression in the environment of the
   application and initialize the value in each place to the value
   of the corresponding operand expression.
3. Evaluate the body of the procedure in the newly created
   environment. The resulting value is the value of the
   application.
Eval and
Apply are
                    Eval
defined in
terms of each
other.
                Apply
10
Object-Oriented
                           Programming

Whirlwind (MIT, 1947-)




                          Sketchpad (Ivan Sutherland, 1963)
Simula
Considered the first
  “object-oriented”
  programming language
Language designed for
  simulation by Kristen
  Nygaard and Ole-Johan
  Dahl (Norway, 1962)
Had special syntax for
  defining classes that
  packages state and
  procedures together
XEROX Palo Alto Research Center (PARC)

1970s:
Bitmapped display
Graphical User Interface
    Steve Jobs paid $1M to visit and
    PARC, and returned to make
    Apple Lisa/Mac
Ethernet
First personal computer (Alto)
PostScript Printers
Object-Oriented Programming
Dynabook, 1972   “Don’t worry about what
                 anybody else is going to do…
                 The best way to predict the
                 future is to invent it. Really
                 smart people with reasonable
                 funding can do just about
                 anything that doesn't violate
                 too many of Newton's Laws!”
                                 — Alan Kay, 1971




                                      (Just a mockup –
                                      couldn’t really
                                      build this in 1972)
Dynabook 1972
Tablet computer intended as tool for learning
Alan Kay wanted children to program it also
Hallway argument, Kay claims you could define
  “the most powerful language in the world in a
  page of code”

Proof: Smalltalk
   Scheme is as powerful, but takes 1½ pages (PS7)
BYTE
Magazine, A
ugust 1981
Smalltalk
Everything is an object
Objects communicate by sending and receiving
  messages
Objects have their own state (which may contain
  other objects)
How do Smalltalkers do 3 + 4?
    send the object 3 the message “+ 4”
Counter in Smalltalk
class name counter
  instance variable names count
  new count <- 0
  next count <- count + 1
  current ^ count
So, who really
  was the first
object-oriented
 programmer?

                  Object-oriented
                  programming is a state
                  of mind where you
                  program thinking about
                  objects that package
                  state and procedures.
Implementing
the Interpreter   Eval

            Apply
evalApplication
To apply a constructed procedure:
1. Construct a new environment, whose
    parent is the environment of the
    applied procedure.
2. For each procedure parameter, create
    a place in the frame of the new
    environment with the name of the
    parameter. Evaluate each operand
    expression in the environment of the
    application and initialize the value in
    each place to the value of the
    corresponding operand expression.
3. Evaluate the body of the procedure in
    the newly created environment. The
    resulting value is the value of the
    application.
Representing Expressions
Use Python Lists:
  ['+', '2', '3'] represents (+ 2 3)

How should we represent (+ 2 (+ 3 4)) ?

              ['+', '2', ['+', '3', '4']]


                                            22
Parsing
parse(<string>)
     list representing the Charme code

 >>> parse("(+ 2 (+ 3 4))")[0]
 ['+', '2', ['+', '3', '4']]
 >>> parse("(define square (lambda (x) (* x x)))")[0]
 ['define', 'square', ['lambda', ['x'], ['*', 'x', 'x']]]

 See Chapter 11 (and the PS7 code) for the details on parsing.


                                                                 23
evalApplication
To apply a constructed procedure:
1. Construct a new environment, whose
    parent is the environment of the
    applied procedure.
2. For each procedure parameter, create
    a place in the frame of the new
    environment with the name of the
    parameter. Evaluate each operand
    expression in the environment of the
    application and initialize the value in
    each place to the value of the
    corresponding operand expression.
3. Evaluate the body of the procedure in
    the newly created environment. The
    resulting value is the value of the
    application.
def evalApplication(expr, env):
 subexprvals = map (lambda sexpr: meval(sexpr, env),
                      expr)
  return mapply(subexprvals[0], subexprvals[1:])




                                                       25
To apply a constructed procedure:             How should we
1. Construct a new environment, whose         represent an
    parent is the environment of the
    applied procedure.                        environment?
2. For each procedure parameter, create
    a place in the frame of the new
    environment with the name of the
    parameter. Evaluate each operand
    expression in the environment of the
    application and initialize the value in
    each place to the value of the
    corresponding operand expression.
3. Evaluate the body of the procedure in
    the newly created environment. The
    resulting value is the value of the
    application.



                                                              26
To apply a constructed procedure:
1. Construct a new environment, whose
    parent is the environment of the
    applied procedure.
2. For each procedure parameter, create
    a place in the frame of the new
    environment with the name of the
    parameter. Evaluate each operand
    expression in the environment of the
    application and initialize the valueEnvironment:
                                 class in
    each place to the value of thedef __init__(self, parent):
    corresponding operand expression.
                                       self._parent = parent
3. Evaluate the body of the procedure in
    the newly created environment.self._frame = {}
                                        The
    resulting value is the value of def addVariable(self, name, value):
                                    the
    application.
                                ...
                              def lookupVariable(self, name):
                                ...

                     Details in Chapter 11 (and Wednesday’s class)
To apply a constructed procedure:
1. Construct a new environment, whose
    parent is the environment of the
    applied procedure.                            def evalApplication(expr, env):
2. For each procedure parameter, create             subexprvals = map (
    a place in the frame of the new                     lambda sexpr: meval(sexpr, env),
    environment with the name of the
                                                        expr)
    parameter. Evaluate each operand
    expression in the environment of the             return mapply(subexprvals[0],
    application and initialize the value in                           subexprvals[1:])
    each place to the value of the
    corresponding operand expression.
3. Evaluate the body of the procedure in
    the newly created environment. The
                                 def mapply(proc, operands):
    resulting value is the value ofif (isPrimitiveProcedure(proc)): ...
                                    the
    application.                   elif isinstance(proc, Procedure):
                                  params = proc.getParams()
                                  newenv = Environment(proc.getEnvironment())
                                  for i in range(0, len(params)):
                                       newenv.addVariable(params[i], operands[i])
                                  ...
def mapply(proc, operands):
                             if (isPrimitiveProcedure(proc)): ...
To apply a constructed procedure:isinstance(proc, Procedure):
                             elif
1. Construct a new environment, whose= proc.getParams()
                                params
    parent is the environment ofnewenv = Environment(proc.getEnvironment())
                                  the
    applied procedure.
                                for i in range(0, len(params)):
2. For each procedure parameter, create
                                      newenv.addVariable(params[i], operands[i])
   a place in the frame of the new
   environment with the name of the
   parameter. Evaluate each operand
   expression in the environment of the
   application and initialize the value in
   each place to the value of the
   corresponding operand expression.
3. Evaluate the body of the procedure in
   the newly created environment. The
   resulting value is the value of the
   application.
def mapply(proc, operands):
                      if (isPrimitiveProcedure(proc)): return proc(operands)
                      elif isinstance(proc, Procedure):
                         params = proc.getParams()
                         newenv = Environment(proc.getEnvironment())
                         for i in range(0, len(params)):
                              newenv.addVariable(params[i], operands[i])
                         return meval(proc.getBody(), newenv)

def evalApplication(expr, env):
 subexprvals = map (
     lambda sexpr: meval(sexpr, env), expr)
  return mapply(subexprvals[0], subexprvals[1:])

         def meval(expr, env):
           …
           elif isApplication(expr):
              return evalApplication(expr, env)
           …
So, who really
  was the first
object-oriented
 programmer?
Object-oriented
programming is
an exceptionally
bad idea which
could only have
originated in
California.
Edsger Dijkstra


                   32
I don’t know how
    many of you have
ever met Dijkstra, but
  you probably know
    that arrogance in
  computer science is
         measured in
       nano-Dijkstras.
             Alan Kay
The people who are the worst at
programming are the people who refuse to
accept the fact that their brains aren't equal
to the task. Their egos keep them from being
great programmers. The more you learn to
compensate for your small brain, the better
a programmer you’ll be. The more humble
you are, the faster you’ll improve.
           Edsger Dijkstra, 1972 Turing Award
          http://www.cs.utexas.edu/users/EWD/ewd03xx/EWD340.PDF
By the word operation, we mean
any process which alters the
mutual relation of two or more
things, be this relation of what
kind it may. This is the most
general definition, and would
include all subjects in the universe.
Again, it might act upon other
things besides number, were
objects found whose mutual
fundamental relations could be
                                           Ada
expressed by those of the abstract
                                    Countess of Lovelace
science of operations...
                                        around 1843
Charge
Meta-linguistic programming is also a
 state of mind!
Read Chapter 11 before Wednesday

PS7 Due next Wednesday (delayed
 from Monday)

                                        36

More Related Content

What's hot

Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Python functions
Python functionsPython functions
Python functionsToniyaP1
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaManoj Kumar kothagulla
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with KotlinAlexey Soshin
 
iPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CiPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CIMC Institute
 
[M4A2] Data Analysis and Interpretation Specialization
[M4A2] Data Analysis and Interpretation Specialization [M4A2] Data Analysis and Interpretation Specialization
[M4A2] Data Analysis and Interpretation Specialization Andrea Rubio
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentationguest0d6229
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with ClojureJohn Stevenson
 
DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019Sabrina Marechal
 
Introduction to Loc
Introduction to LocIntroduction to Loc
Introduction to LocIder Zheng
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector classNontawat Wongnuk
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 

What's hot (20)

All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Python functions
Python functionsPython functions
Python functions
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
iPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-CiPhone Programming [1/17] : Objective-C
iPhone Programming [1/17] : Objective-C
 
Dagger1
Dagger1Dagger1
Dagger1
 
[M4A2] Data Analysis and Interpretation Specialization
[M4A2] Data Analysis and Interpretation Specialization [M4A2] Data Analysis and Interpretation Specialization
[M4A2] Data Analysis and Interpretation Specialization
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Understanding Subroutines and Functions in VB6
Understanding Subroutines and Functions in VB6Understanding Subroutines and Functions in VB6
Understanding Subroutines and Functions in VB6
 
Thinking Functionally with Clojure
Thinking Functionally with ClojureThinking Functionally with Clojure
Thinking Functionally with Clojure
 
DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019
 
Introduction to Loc
Introduction to LocIntroduction to Loc
Introduction to Loc
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 

Viewers also liked

Viewers also liked (20)

Portfólió mátrix
Portfólió mátrixPortfólió mátrix
Portfólió mátrix
 
Goldlife9999-HU
Goldlife9999-HUGoldlife9999-HU
Goldlife9999-HU
 
SWOT elemzés - Stratégiai tervezés
SWOT elemzés - Stratégiai tervezésSWOT elemzés - Stratégiai tervezés
SWOT elemzés - Stratégiai tervezés
 
A Lelkigondozas Modszertana
A Lelkigondozas ModszertanaA Lelkigondozas Modszertana
A Lelkigondozas Modszertana
 
Dyslexia and specific learning difficulties
Dyslexia and specific learning difficultiesDyslexia and specific learning difficulties
Dyslexia and specific learning difficulties
 
Instrukcio a terkephez
Instrukcio a terkephezInstrukcio a terkephez
Instrukcio a terkephez
 
Newspaper BestNews
Newspaper BestNewsNewspaper BestNews
Newspaper BestNews
 
Talent_Projektek
Talent_ProjektekTalent_Projektek
Talent_Projektek
 
21 neurologiaiharmonia
21 neurologiaiharmonia21 neurologiaiharmonia
21 neurologiaiharmonia
 
Ima_a_gyerekekert
Ima_a_gyerekekertIma_a_gyerekekert
Ima_a_gyerekekert
 
21 tanulas
21 tanulas21 tanulas
21 tanulas
 
Digitalis konferencia 2016
Digitalis konferencia 2016Digitalis konferencia 2016
Digitalis konferencia 2016
 
Aktivmatrix
AktivmatrixAktivmatrix
Aktivmatrix
 
21 olvasas
21 olvasas21 olvasas
21 olvasas
 
Talent_rendszer
Talent_rendszerTalent_rendszer
Talent_rendszer
 
Netgeneration2
Netgeneration2Netgeneration2
Netgeneration2
 
Manipulator akcioban
Manipulator akciobanManipulator akcioban
Manipulator akcioban
 
Kulonlegesek
KulonlegesekKulonlegesek
Kulonlegesek
 
Tehet_Akadaly
Tehet_AkadalyTehet_Akadaly
Tehet_Akadaly
 
Érdeklődes, motiváció
Érdeklődes, motivációÉrdeklődes, motiváció
Érdeklődes, motiváció
 

Similar to Class 32: Interpreters

Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7ashhadiqbal
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
 
Prelim Project OOP
Prelim Project OOPPrelim Project OOP
Prelim Project OOPDwight Sabio
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R LearningKumar P
 
Class 4: Making Procedures
Class 4: Making ProceduresClass 4: Making Procedures
Class 4: Making ProceduresDavid Evans
 
Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...NILESH VERMA
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdffashionbigchennai
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Tiểu Hổ
 

Similar to Class 32: Interpreters (20)

Ecet 370 week 1 lab
Ecet 370 week 1 labEcet 370 week 1 lab
Ecet 370 week 1 lab
 
Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7Comp 220 ilab 5 of 7
Comp 220 ilab 5 of 7
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Prelim Project OOP
Prelim Project OOPPrelim Project OOP
Prelim Project OOP
 
advancedR.pdf
advancedR.pdfadvancedR.pdf
advancedR.pdf
 
Advanced r
Advanced rAdvanced r
Advanced r
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R Learning
 
Advanced R cheat sheet
Advanced R cheat sheetAdvanced R cheat sheet
Advanced R cheat sheet
 
Class 4: Making Procedures
Class 4: Making ProceduresClass 4: Making Procedures
Class 4: Making Procedures
 
Siguccs20101026
Siguccs20101026Siguccs20101026
Siguccs20101026
 
React native
React nativeReact native
React native
 
Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...Demystifying NLP Transformers: Understanding the Power and Architecture behin...
Demystifying NLP Transformers: Understanding the Power and Architecture behin...
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
 
Hub102 - JS - Lesson3
Hub102 - JS - Lesson3Hub102 - JS - Lesson3
Hub102 - JS - Lesson3
 

More from David Evans

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!David Evans
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksDavid Evans
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeDavid Evans
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in BitcoinDavid Evans
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm ConfirmationsDavid Evans
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting TransactionsDavid Evans
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in ParadiseDavid Evans
 
Mining Economics
Mining EconomicsMining Economics
Mining EconomicsDavid Evans
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More ParanoidDavid Evans
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key SignaturesDavid Evans
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to CryptographyDavid Evans
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?David Evans
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the MassesDavid Evans
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of ReserveDavid Evans
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!David Evans
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinDavid Evans
 

More from David Evans (20)

Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!Cryptocurrency Jeopardy!
Cryptocurrency Jeopardy!
 
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for CypherpunksTrick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
Trick or Treat?: Bitcoin for Non-Believers, Cryptocurrencies for Cypherpunks
 
Hidden Services, Zero Knowledge
Hidden Services, Zero KnowledgeHidden Services, Zero Knowledge
Hidden Services, Zero Knowledge
 
Anonymity in Bitcoin
Anonymity in BitcoinAnonymity in Bitcoin
Anonymity in Bitcoin
 
Midterm Confirmations
Midterm ConfirmationsMidterm Confirmations
Midterm Confirmations
 
Scripting Transactions
Scripting TransactionsScripting Transactions
Scripting Transactions
 
How to Live in Paradise
How to Live in ParadiseHow to Live in Paradise
How to Live in Paradise
 
Bitcoin Script
Bitcoin ScriptBitcoin Script
Bitcoin Script
 
Mining Economics
Mining EconomicsMining Economics
Mining Economics
 
Mining
MiningMining
Mining
 
The Blockchain
The BlockchainThe Blockchain
The Blockchain
 
Becoming More Paranoid
Becoming More ParanoidBecoming More Paranoid
Becoming More Paranoid
 
Asymmetric Key Signatures
Asymmetric Key SignaturesAsymmetric Key Signatures
Asymmetric Key Signatures
 
Introduction to Cryptography
Introduction to CryptographyIntroduction to Cryptography
Introduction to Cryptography
 
Class 1: What is Money?
Class 1: What is Money?Class 1: What is Money?
Class 1: What is Money?
 
Multi-Party Computation for the Masses
Multi-Party Computation for the MassesMulti-Party Computation for the Masses
Multi-Party Computation for the Masses
 
Proof of Reserve
Proof of ReserveProof of Reserve
Proof of Reserve
 
Silk Road
Silk RoadSilk Road
Silk Road
 
Blooming Sidechains!
Blooming Sidechains!Blooming Sidechains!
Blooming Sidechains!
 
Useful Proofs of Work, Permacoin
Useful Proofs of Work, PermacoinUseful Proofs of Work, Permacoin
Useful Proofs of Work, Permacoin
 

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Class 32: Interpreters

  • 1. Class 32: Interpreters cs1120 Fall 2011 David Evans 7 November 2011
  • 2. Plan Implementing Interpreters History of Object-Oriented Programming Problem Set 7: posted today, due Monday 14 November. • Understand the Charme interpreter (described in Chapter 11) • Modify it to change the evaluation rules 2
  • 3. Building a Language Design the grammar What strings are in the language? Use BNF to describe all the strings in the language Make up the evaluation rules Describe what every string in the language means Build an evaluator Implement a procedure that takes a string in the language as input and an environment and outputs its value: meval: String Environment → Value
  • 4. Is this an exaggeration? It is no exaggeration to regard this as the most fundamental idea in programming: The evaluator, which determines the meaning of expressions in the programming language, is just another program. To appreciate this point is to change our images of ourselves as programmers. We come to see ourselves as designers of Abelson and languages, rather than only users of Sussman, Structure and languages designed by others. Interpretation of Computer Programs (p. 360)
  • 5. Building an Evaluator To build an evaluator we need to: Figure out how to represent data in programs What is a procedure, frame, environment, etc. Implement the evaluation rules For each evaluation rule, define a procedure that follows the behavior of that rule. Next: we’ll look at a high-level how the application rule is implemented Wednesday and Chapter 11: detailed walk-through of the interpreter
  • 6. Core of the Evaluator 6
  • 7. def meval(expr, env): if isPrimitive(expr): return evalPrimitive(expr) elif isIf(expr): return evalIf(expr, env) elif isDefinition(expr): evalDefinition(expr, env) elif isName(expr): return evalName(expr, env) elif isLambda(expr): return evalLambda(expr, env) elif isApplication(expr): return evalApplication(expr, env) else: error ('Unknown expression type: ' + str(expr))
  • 8. Stateful Application Rule To apply a constructed procedure: 1. Construct a new environment, whose parent is the environment of the applied procedure. 2. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the value in each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application.
  • 9. Eval and Apply are Eval defined in terms of each other. Apply
  • 10. 10
  • 11. Object-Oriented Programming Whirlwind (MIT, 1947-) Sketchpad (Ivan Sutherland, 1963)
  • 12. Simula Considered the first “object-oriented” programming language Language designed for simulation by Kristen Nygaard and Ole-Johan Dahl (Norway, 1962) Had special syntax for defining classes that packages state and procedures together
  • 13. XEROX Palo Alto Research Center (PARC) 1970s: Bitmapped display Graphical User Interface Steve Jobs paid $1M to visit and PARC, and returned to make Apple Lisa/Mac Ethernet First personal computer (Alto) PostScript Printers Object-Oriented Programming
  • 14. Dynabook, 1972 “Don’t worry about what anybody else is going to do… The best way to predict the future is to invent it. Really smart people with reasonable funding can do just about anything that doesn't violate too many of Newton's Laws!” — Alan Kay, 1971 (Just a mockup – couldn’t really build this in 1972)
  • 15. Dynabook 1972 Tablet computer intended as tool for learning Alan Kay wanted children to program it also Hallway argument, Kay claims you could define “the most powerful language in the world in a page of code” Proof: Smalltalk Scheme is as powerful, but takes 1½ pages (PS7)
  • 17. Smalltalk Everything is an object Objects communicate by sending and receiving messages Objects have their own state (which may contain other objects) How do Smalltalkers do 3 + 4? send the object 3 the message “+ 4”
  • 18. Counter in Smalltalk class name counter instance variable names count new count <- 0 next count <- count + 1 current ^ count
  • 19. So, who really was the first object-oriented programmer? Object-oriented programming is a state of mind where you program thinking about objects that package state and procedures.
  • 21. evalApplication To apply a constructed procedure: 1. Construct a new environment, whose parent is the environment of the applied procedure. 2. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the value in each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application.
  • 22. Representing Expressions Use Python Lists: ['+', '2', '3'] represents (+ 2 3) How should we represent (+ 2 (+ 3 4)) ? ['+', '2', ['+', '3', '4']] 22
  • 23. Parsing parse(<string>) list representing the Charme code >>> parse("(+ 2 (+ 3 4))")[0] ['+', '2', ['+', '3', '4']] >>> parse("(define square (lambda (x) (* x x)))")[0] ['define', 'square', ['lambda', ['x'], ['*', 'x', 'x']]] See Chapter 11 (and the PS7 code) for the details on parsing. 23
  • 24. evalApplication To apply a constructed procedure: 1. Construct a new environment, whose parent is the environment of the applied procedure. 2. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the value in each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application.
  • 25. def evalApplication(expr, env): subexprvals = map (lambda sexpr: meval(sexpr, env), expr) return mapply(subexprvals[0], subexprvals[1:]) 25
  • 26. To apply a constructed procedure: How should we 1. Construct a new environment, whose represent an parent is the environment of the applied procedure. environment? 2. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the value in each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application. 26
  • 27. To apply a constructed procedure: 1. Construct a new environment, whose parent is the environment of the applied procedure. 2. For each procedure parameter, create a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the valueEnvironment: class in each place to the value of thedef __init__(self, parent): corresponding operand expression. self._parent = parent 3. Evaluate the body of the procedure in the newly created environment.self._frame = {} The resulting value is the value of def addVariable(self, name, value): the application. ... def lookupVariable(self, name): ... Details in Chapter 11 (and Wednesday’s class)
  • 28. To apply a constructed procedure: 1. Construct a new environment, whose parent is the environment of the applied procedure. def evalApplication(expr, env): 2. For each procedure parameter, create subexprvals = map ( a place in the frame of the new lambda sexpr: meval(sexpr, env), environment with the name of the expr) parameter. Evaluate each operand expression in the environment of the return mapply(subexprvals[0], application and initialize the value in subexprvals[1:]) each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The def mapply(proc, operands): resulting value is the value ofif (isPrimitiveProcedure(proc)): ... the application. elif isinstance(proc, Procedure): params = proc.getParams() newenv = Environment(proc.getEnvironment()) for i in range(0, len(params)): newenv.addVariable(params[i], operands[i]) ...
  • 29. def mapply(proc, operands): if (isPrimitiveProcedure(proc)): ... To apply a constructed procedure:isinstance(proc, Procedure): elif 1. Construct a new environment, whose= proc.getParams() params parent is the environment ofnewenv = Environment(proc.getEnvironment()) the applied procedure. for i in range(0, len(params)): 2. For each procedure parameter, create newenv.addVariable(params[i], operands[i]) a place in the frame of the new environment with the name of the parameter. Evaluate each operand expression in the environment of the application and initialize the value in each place to the value of the corresponding operand expression. 3. Evaluate the body of the procedure in the newly created environment. The resulting value is the value of the application.
  • 30. def mapply(proc, operands): if (isPrimitiveProcedure(proc)): return proc(operands) elif isinstance(proc, Procedure): params = proc.getParams() newenv = Environment(proc.getEnvironment()) for i in range(0, len(params)): newenv.addVariable(params[i], operands[i]) return meval(proc.getBody(), newenv) def evalApplication(expr, env): subexprvals = map ( lambda sexpr: meval(sexpr, env), expr) return mapply(subexprvals[0], subexprvals[1:]) def meval(expr, env): … elif isApplication(expr): return evalApplication(expr, env) …
  • 31. So, who really was the first object-oriented programmer?
  • 32. Object-oriented programming is an exceptionally bad idea which could only have originated in California. Edsger Dijkstra 32
  • 33. I don’t know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras. Alan Kay
  • 34. The people who are the worst at programming are the people who refuse to accept the fact that their brains aren't equal to the task. Their egos keep them from being great programmers. The more you learn to compensate for your small brain, the better a programmer you’ll be. The more humble you are, the faster you’ll improve. Edsger Dijkstra, 1972 Turing Award http://www.cs.utexas.edu/users/EWD/ewd03xx/EWD340.PDF
  • 35. By the word operation, we mean any process which alters the mutual relation of two or more things, be this relation of what kind it may. This is the most general definition, and would include all subjects in the universe. Again, it might act upon other things besides number, were objects found whose mutual fundamental relations could be Ada expressed by those of the abstract Countess of Lovelace science of operations... around 1843
  • 36. Charge Meta-linguistic programming is also a state of mind! Read Chapter 11 before Wednesday PS7 Due next Wednesday (delayed from Monday) 36