Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
|
|
- Claud Alexander Miller
- 5 years ago
- Views:
Transcription
1 Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters) analyse abstract syntax trees. Compilers very well understood In fact, there exist compiler compilers Example: YACC (yet another compiler compiler) Copyright Bill Havens 1
2 Expression Syntax Extended An abstract syntax expresses the structure of the concrete syntax without the details. Example: extended syntax for Scheme expressions Includes literals (constant numbers) <exp> ::= <number> <symbol> (lambda (<symbol>) <exp>) (<exp> <exp>) We would define an abstract datatype for this grammar as follows: (define-datatype expression expression? (lit-exp (datum number?)) (var-exp (id symbol?)) (lambda-exp (id symbol?) (body expression?)) (app-exp (rator expression?) (rand expression?))) Now lets parse sentences in the language specified by the BNF grammar into abstract syntax trees Copyright Bill Havens 2
3 Parser for Extended Expressions Here is an example parser for the lambda expression language above: (define parse-expression (lambda (datum) (cond ((number? datum) (lit-exp datum)) ((symbol? datum) (var-exp datum)) ((pair? datum) (if (eqv? (car datum) 'lambda) (lambda-exp (caadr datum) (parse-expression (caddr datum))) (app-exp (parse-expression (car datum)) (parse-expression (cadr datum))))) (else (eopl:error 'parse-expression "Invalid concrete syntax ~s" datum))))) Fortunately, Schme (read) function does most of the hard work Identifies tokens in input stream (eg- (, ), identifiers, strings) Converts parenthesized structures into dotted-pairs and proper lists Copyright Bill Havens 3
4 Example All we have to do is convert between the lists that read produces into abstract syntax trees (parse-expression (foo x)) (parse-expression 3) (parse-expression (lambda (x) (lambda (y) (cons x y)))) Let s see how these work in Dr. Scheme... Hard to see! Lets implement an un-parse procedure to take the abstract syntax tree apart Turns back into concrete Scheme syntax (define unparse-expression (lambda (exp) (cases expression exp (lit-exp (datum) datum) (var-exp (id) id) (lambda-exp (id body) (list 'lambda (list id) (unparse-expression body))) (app-exp (rator rand) (list (unparse-expression rator) (unparse-expression rand)))))) Copyright Bill Havens 4
5 Environments Introduction Consider evaluating the following expression: (+ x 3) How does the interpreter know the value of variable x? Variable bindings stored in a dictionary (aka- symbol table) called an environment Definition: An environment is a function that maps variable names to their current bindings. - Interpreter: mapping variables to their current values - Compiler: mapping variables to their lexical addresses We denote an environment by a finite set of bindings, each having the form s v. Example: env = { x 3, y (a b c), z hello } Environment function can be applied to an argument symbol returning its binding in that enviornment Example: env(y) = (a b c) But env(w) = error - undefined variable Copyright Bill Havens 5
6 Nested Environments Block structured languages (eg- C, Java, Scheme) allow nested blocks Example in C: int foo (int z) { int x; float y; if (x < z) { float y = 3.0;... } else { print x;... }; for (int x = 0; x < z; x++) { print x+y;...} } How many different environments are there in this example? What are the variable bindings in each environment? Are there any holes in any environment? Since blocks can be nested, we need to nest environments as well Each scoping block needs to have its own environment. The environment of a nested block must to refer to the environments of the enclosing blocks recursively. Copyright Bill Havens 6
7 Introduction Recursive Environments We can think of an environment as extending its enclosing environment. If you look something up in the environment and don't find it, look in the enclosing environment. Recursion has to stop, so we need the concept of an empty environment We can think of an environment then as an inductively-defined type: The BNF for <environment> <environment> ::= ( ) ( {<variable>, <value>}* <environment>) An environment is either empty or its a set of (variable,value) pairs that extend an existing enclosing environment. Copyright Bill Havens 7
8 Abstract Environments Basic Idea An abstract environment requires: 1. a function for creating an empty environment 2. An operator for extending an environment with new bindings 3. An operator for accessing the binding of a variable in an environment Operator interfaces: ;; returns an empty environment (define empty-env (lambda ()... )) ;; returns an environment that extends env (define extend-env (lambda (vars vals env)... )) ;; returns the value of the variable "var" in "env" (define apply-env (lambda (env var)... )) Copyright Bill Havens 8
9 Usage (define first-env (empty-env)) (define second-env (extend-env '(a b) '(1 2) first-env) (define third-env (extend-env '(c d b) '(3 4 5) second-env) (apply-env first-env 'a) ; returns an error (apply-env second-env 'a) ; returns 1 (apply-env third-env 'a) ; returns 1 (same "a") (apply-env second-env 'b) ; returns 2 (apply-env third-env 'b) ; returns 5 (different "b") Copyright Bill Havens 9
10 Implementing Environments Procedural versus Datatype implementations Basis for Object-Oriented Programming Language (OOPL) concept Data is only accessbile via a procedural interface (eg- methods in Java) Actual implementation of data is hidden by the interface Implementation can be changed without breaking code Procedural Implementation Environments are a function: f(variable) = value. The empty environment is a function that when called always returns an error! The method (empty-env) returns an environment with no bindings (define empty-env (lambda () (lambda (sym) (eopl:error 'apply-env "No binding for ~s" sym)))) Copyright Bill Havens 10
11 Extending an Environment An extended environment is also a function which returns a value for a specified variable. If the variable you're looking for is one defined in that environment, it returns the corresponding value; otherwise, it calls the environment function which it extends Here is an implementation: (define extend-env (lambda (syms vals env) (lambda (sym) (let ((pos (list-find-position sym syms))) (if (number? pos) (list-ref vals pos) (apply-env env sym)))))) Note that the bindings are represented as corresponding lists of variables and values Method extend-env returns a function that when called searches these lists If desired variable is not found in this environment then extend-env is called recursively on the enclosing environment Copyright Bill Havens 11
12 Helper functions Method (list-find-position sym syms) searches the list of variable names (syms) to find the desired variable (sym) Returns a zero-based index on success and #f on failure (Scheme convention) (define list-find-position (lambda (sym los) (list-index (lambda (sym1) (eqv? sym1 sym)) los))) Method (list-index pred ls) is a higher-order function which applies a specified predicate pred to a list ls (define list-index (lambda (pred ls) (cond ((null? ls) #f) ((pred (car ls)) 0) (else (let ((list-index-r (list-index pred (cdr ls)))) (if (number? list-index-r) (+ list-index-r 1) #f)))))) Comment: what is peculiar about this method implementation? Copyright Bill Havens 12
13 Recoding function list-index Very inefficient implementation when an error is detected Need an exception thrown instead Why not use call/cc mechanism? Reminder: (call/cc <lambda>) calls a function <lambda> of one argument which is the continuation of the call/cc expression. Applying the continuation function immediately exits from the call/cc Recoding using call/cc (define list-index (lambda (pred ls) (call/cc (lambda (exit) (list-index1 pred ls exit))))) (define list-index1 (lambda (pred ls exit) (cond ((null? ls) (exit #f)) ((pred (car ls)) 0) (else (+ 1 (list-index1 pred (cdr ls) exit)))))) Much simpler! But can you improve it further? Use tail recursion! Copyright Bill Havens 13
14 Applying a procedural environment Just call the function on the variable to be accessed (define apply-env (lambda (env sym) (env sym))) Example: (apply-env (extend-env (x z) (1 3) (extend-env (y z) (2 2) (extend-env (x y) (4 7) (empty-env)))) y) Copyright Bill Havens 14
15 Overview Datatype Implementation Abstract datatype representation Declarative view of data (cf- procedural view) using the define-datatype construct: (define-datatype environment environment? (empty-env-record) (extended-env-record (syms (list-of symbol?)) (vals (list-of scheme-value?)) (env environment?))) Defining trivial predicate for any Scheme value: (define scheme-value? (lambda (v) #t)) Copyright Bill Havens 15
16 Empty Environment Creating an empty environment is pretty simple just use the empty-env-record constructor: (define empty-env (lambda () (empty-env-record))) Extending an Environment Extending an environment is also straightforward Use the extended-env-record constructor: (define extend-env (lambda (syms vals env) (extended-env-record syms vals env))) Copyright Bill Havens 16
17 Applying the Environment Applying the environment is a little more complicated Need to traverse the data structures instead of just calling a function. (define apply-env (lambda (env sym) (cases environment env (empty-env-record () (eopl:error 'apply-env "No binding for ~s" sym)) (extended-env-record (syms vals env) (let ((pos (list-find-position sym syms))) (if (number? pos) (list-ref vals pos) (apply-env env sym))))))) Chapter 3 will use the abstract notion of an environment Implementation is irrelevant! Copyright Bill Havens 17
Lecture 12: Conditional Expressions and Local Binding
Lecture 12: Conditional Expressions and Local Binding Introduction Corresponds to EOPL 3.3-3.4 Please review Version-1 interpreter to make sure that you understand how it works Now we will extend the basic
More informationData Abstraction. An Abstraction for Inductive Data Types. Philip W. L. Fong.
Data Abstraction An Abstraction for Inductive Data Types Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Introduction This lecture
More informationLecture08: Scope and Lexical Address
Lecture08: Scope and Lexical Address Free and Bound Variables (EOPL 1.3.1) Given an expression E, does a particular variable reference x appear free or bound in that expression? Definition: A variable
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationCS 342 Lecture 8 Data Abstraction By: Hridesh Rajan
CS 342 Lecture 8 Data Abstraction By: Hridesh Rajan 1 Com S 342 so far So far we have studied: Language design goals, Basic functional programming, Flat recursion over lists, Notion of Scheme procedures
More information6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson
6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator
More informationCS 275 Name Final Exam Solutions December 16, 2016
CS 275 Name Final Exam Solutions December 16, 2016 You may assume that atom? is a primitive procedure; you don t need to define it. Other helper functions that aren t a standard part of Scheme you need
More informationA Brief Introduction to Scheme (II)
A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data
More information6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter
6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,
More informationIntroduction to Scheme
How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free
More informationComputer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing
Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible
More informationWhy do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.
.00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do
More informationLecture 3: Expressions
CS 7400 September 23 30, 2009 Dr. Wand Readings: EOPL3, Secs. 3.1 3.5 Lecture 3: Expressions Key Concepts: syntax and semantics expressed and denoted values expressions environment specifying the behavior
More informationScheme in Scheme: The Metacircular Evaluator Eval and Apply
Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,
More informationProject 2: Scheme Interpreter
Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same
More informationScheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7
Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions
More informationLecture 16: Object Programming Languages
Lecture 16: Object Programming Languages Introduction Corresponds to EOPL 5.1 and 5.2 Goal: to introduce Object Oriented Programming Language (OOPL) concepts using the EOPL extensible language framework
More informationCOP4020 Programming Assignment 1 - Spring 2011
COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to
More informationSyntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want
Computer Science 21b (Spring Term, 2017) Structure and Interpretation of Computer Programs Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want Here is one of the big ideas
More informationMid-Term 2 Grades
Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for
More informationCS 360 Programming Languages Interpreters
CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like
More informationSTREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?
STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? 2. How does memoization work? 3. Is a cons-stream a special form? Practice with Streams 1. Define a procedure (ones) that, when run
More informationComp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018
Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters Corky Cartwright January 26, 2018 Denotational Semantics The primary alternative to syntactic semantics is denotational semantics.
More informationCSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures
CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught
More information6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane Boning Further Variations on a Scheme Beyond Scheme
More informationPattern Matching for Scheme
Pattern Matching for Scheme Andrew K. Wright March 1996 Department of Computer Science MS 132 Rice University 6100 Main Street Houston, Texas 77005-1892 Contents 1 Match 1 1.1 Definition... 1 1.1.1 Patterns...
More information1 of 5 5/11/2006 12:10 AM CS 61A Spring 2006 Midterm 2 solutions 1. Box and pointer. Note: Please draw actual boxes, as in the book and the lectures, not XX and X/ as in these ASCII-art solutions. Also,
More informationComp 311: Sample Midterm Examination
Comp 311: Sample Midterm Examination October 29, 2007 Name: Id #: Instructions 1. The examination is closed book. If you forget the name for a Scheme operation, make up a name for it and write a brief
More informationPrinciples of Programming Languages
Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,
More informationAn Explicit-Continuation Metacircular Evaluator
Computer Science (1)21b (Spring Term, 2018) Structure and Interpretation of Computer Programs An Explicit-Continuation Metacircular Evaluator The vanilla metacircular evaluator gives a lot of information
More informationUser-defined Functions. Conditional Expressions in Scheme
User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment
More informationCS 415 Midterm Exam Spring SOLUTION
CS 415 Midterm Exam Spring 2005 - SOLUTION Name Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you
More informationCS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang
CS61A Notes Week 6B: Streams Streaming Along A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the
More informationFrom Syntactic Sugar to the Syntactic Meth Lab:
From Syntactic Sugar to the Syntactic Meth Lab: Using Macros to Cook the Language You Want a V E N E TRUT H Brandeis S PA R T U N T O I T S I N N E R M OS T COMPUTER SCIENCE 21B: Structure and Interpretation
More informationCSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)
CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent
More informationAn Introduction to Scheme
An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification
More informationEssentials of Programming Languages Language
Essentials of Programming Languages Language Version 5.3 August 6, 2012 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly
More informationEssentials of Programming Languages Language
Essentials of Programming Languages Language Version 6.90.0.26 April 20, 2018 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly
More informationCSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings
More informationC311 Lab #3 Representation Independence: Representation Independent Interpreters
C311 Lab #3 Representation Independence: Representation Independent Interpreters Will Byrd webyrd@indiana.edu February 5, 2005 (based on Professor Friedman s lecture on January 29, 2004) 1 Introduction
More informationLECTURE 3. Compiler Phases
LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent
More informationPrinciples of Programming Languages
Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished
More informationCS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan
CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,
More informationLisp. Versions of LISP
Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major
More informationIntroduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples
Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the
More informationStreams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson
Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation
More informationDeferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.
Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+
More informationStatic Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1
Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationSTREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?
STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? A stream is an element and a promise to evaluate the rest of the stream. Streams are a clever idea that allows one to use sequence
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationTurtles All The Way Down
Turtles All The Way Down Bertrand Russell had just finished giving a public lecture on the nature of the universe. An old woman said Prof. Russell, it is well known that the earth rests on the back of
More informationLecture 2: Data Types and their Representations; Syntax: Scanning and Parsing
CS 7400 September 16-21, 2009 Dr. Wand Readings: EOPL, Chap. 2 Lecture 2: Data Types and their Representations; Syntax: Scanning and Parsing Key Concepts: Data types The Data Abstraction Principle Interface,
More informationScheme Basics > (butfirst '(help!)) ()
Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst
More informationAnnouncements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.
The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper
More informationCS 415 Midterm Exam Spring 2002
CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming
More informationThe Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.
The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees
More informationProcedures. EOPL3: Section 3.3 PROC and App B: SLLGEN
Procedures EOPL3: Section 3.3 PROC and App B: SLLGEN The PROC language Expression ::= proc (Identifier) Expression AST: proc-exp (var body) Expression ::= (Expression Expression) AST: call-exp (rator rand)
More information;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for
Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy
More informationSyntax and Grammars 1 / 21
Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?
More informationUsing Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add
Using Symbols in Expressions (1) (define z y) z Symbol y z ==> y prints as (+ x 3) evaluate sub-expressions... PrimProc Number Number ( ) machine code to add 23 3 Number 26 apply... ==> 26 prints as 1
More informationCS61A Midterm 2 Review (v1.1)
Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the
More informationCSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8
Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationexp ::= (match exp clause :::) j clause :::) j * clause :::) j (match-let ([pat exp] :::) body) j (match-let* ([pat exp] :::) body) j (match-letrec ([
Pattern Matching for Scheme Andrew K. Wright and Bruce F. Duba Department of Computer Science Rice University Houston, TX 77251-1892 Version 1.12, May 24, 1995 Please direct questions or bug reports regarding
More informationA LISP Interpreter in ML
UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,
More informationCSE341, Spring 2013, Final Examination June 13, 2013
CSE341, Spring 2013, Final Examination June 13, 2013 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, except for both sides of one 8.5x11in piece of paper. Please stop
More informationFunctional Programming
Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used
More informationBuilding a system for symbolic differentiation
Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)
More informationProject 1: Scheme Pretty-Printer
Project 1: Scheme Pretty-Printer CSC 4101, Fall 2017 Due: 7 October 2017 For this programming assignment, you will implement a pretty-printer for a subset of Scheme in either C++ or Java. The code should
More informationCS 415 Midterm Exam Fall 2003
CS 415 Midterm Exam Fall 2003 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you can to
More informationThe Typed Racket Guide
The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce
More informationMidterm 2 Solutions Many acceptable answers; one was the following: (defparameter g1
Midterm 2 Solutions 1. [20 points] Consider the language that consist of possibly empty lists of the identifier x enclosed by parentheses and separated by commas. The language includes { () (x) (x,x) (x,x,x)
More informationNormal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?
Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated
More informationECE251 Midterm practice questions, Fall 2010
ECE251 Midterm practice questions, Fall 2010 Patrick Lam October 20, 2010 Bootstrapping In particular, say you have a compiler from C to Pascal which runs on x86, and you want to write a self-hosting Java
More informationProgramming Languages
Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages
More informationCSc 520 Principles of Programming Languages
CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian
More informationAnatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?
Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator
More information1. For every evaluation of a variable var, the variable is bound.
7 Types We ve seen how we can use interpreters to model the run-time behavior of programs. Now we d like to use the same technology to analyze or predict the behavior of programs without running them.
More informationThe role of semantic analysis in a compiler
Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationPL Revision overview
PL Revision overview Course topics Parsing G = (S, P, NT, T); (E)BNF; recursive descent predictive parser (RDPP) Lexical analysis; Syntax and semantic errors; type checking Programming language structure
More informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
More informationCMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics
Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.
More informationCSCE 314 Programming Languages. Type System
CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be
More informationOverview. CS301 Session 3. Problem set 1. Thinking recursively
Overview CS301 Session 3 Review of problem set 1 S-expressions Recursive list processing Applicative programming A look forward: local variables 1 2 Problem set 1 Don't use begin unless you need a side
More informationLexical vs. Dynamic Scope
Intro Lexical vs. Dynamic Scope where do I point to? Remember in Scheme whenever we call a procedure we pop a frame and point it to where the procedure points to (its defining environment). This is called
More informationThis exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.
CS 61A Final Exam May 16, 2008 Your name login: cs61a This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions. This booklet contains 18 numbered pages including
More informationTypescript on LLVM Language Reference Manual
Typescript on LLVM Language Reference Manual Ratheet Pandya UNI: rp2707 COMS 4115 H01 (CVN) 1. Introduction 2. Lexical Conventions 2.1 Tokens 2.2 Comments 2.3 Identifiers 2.4 Reserved Keywords 2.5 String
More informationCS450 - Structure of Higher Level Languages
Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.
More informationCS61A Notes Disc 11: Streams Streaming Along
CS61A Notes Disc 11: Streams Streaming Along syntax in lecture and in the book, so I will not dwell on that. Suffice it to say, streams is one of the most mysterious topics in CS61A, trust than whatever
More informationBuilding a system for symbolic differentiation
Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)
More informationBelow are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.
6.001, Fall Semester, 2002 Quiz II Sample solutions 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationEvaluating Scheme Expressions
Evaluating Scheme Expressions How Scheme evaluates the expressions? (procedure arg 1... arg n ) Find the value of procedure Find the value of arg 1 Find the value of arg n Apply the value of procedure
More informationJim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4
Jim Lambers ENERGY 211 / CME 211 Autumn Quarter 2008-09 Programming Project 4 This project is due at 11:59pm on Friday, October 31. 1 Introduction In this project, you will do the following: 1. Implement
More informationLECTURE 16. Functional Programming
LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Fall, 2001 Prof. R. Fateman SUGGESTED S CS 164 Final Examination: December 18, 2001, 8-11AM
More informationB The SLLGEN Parsing System
B The SLLGEN Parsing System Programs are just strings of characters. In order to process a program, we need to group these characters into meaningful units. This grouping is usually divided into two stages:
More information