Lecture 21: Relational Programming II. November 15th, 2011
|
|
- Nathaniel Barber
- 5 years ago
- Views:
Transcription
1 Lecture 21: Relational Programming II November 15th, 2011
2 Lecture Outline Relational Programming contd The Relational Model of Computation Programming with choice and Solve Search Strategies Relational Parsing Summary
3 Relational Programming contd How about Append is it relational? Example (Procedure Append) proc {Append List1 List2 List3} case List1 of nil then List3 = List2 [] Head Tail then List4 in List3 = Head List4 {Append Tail List2 List4} end end Append is not relational: 1 it will work if List2 or List3 (or both) are (partially) unbound; it won t work if List1 is unbound or is (partially) unbound, because of blocking during pattern matching. 1 The smart Append the one with pattern matching involving both List1 and List2; see lecture 5 wouldn t work if List1 or List2 (or both) were partial lists.
4 Relational Programming contd We can try to improve Append using, e.g., exceptions. Example (Procedure Append improved ) proc {Append List1 List2 List3} try List1 = nil List2 = List3 catch _ then Head Tail1 Tail3 in List1 = Head Tail1 List3 = Head Tail3 {Append Tail1 List2 Tail3} end end The idea is to try to unify List1 with nil and then List2 with List3, or do the recursive call when the unification fails: instead of branching with the blocking case, we do branching with try/catch. Unfortunately, this version doesn t handle correctly the case where List1 is (partially) unbound.
5 Relational Programming contd Example (Procedure Append improved contd) {Browse {Append [1] [2 3] $}} % prints [1 2 3] {Browse {Append [1] $ [1 2 3]}} % prints [2 3] {Browse List2 List3} {Append [1] List2 List3} List3 = [1 2 3] % prints List2#List3 % updates to List2#(1 List2) % updates to [2 3]#(1 2 3 nil) {Browse {Append $ [2 3] [1 2 3]}} % fails at nil = _ _ If List1 is unbound, it becomes immediately bound to nil. This binding is not undone if List2 = List3 fails. 2 For Append to be relational, we need a tool for undoing bindings, or for performing multiple independent tentative bindings for the same variable. 2 Recall, searching for a catch clause we are unwinding the stack, but bindings are not undone.
6 Relational Programming contd In Prolog, implementing the relational append is trivial. Example (Relational append, Prolog) code/append.pl append([], List, List). append([head Tail1], List, [Head Tail2]) :- append(tail1, List, Tail2). consult(append). % load the program append([1], [2,3], List). % List = [1,2,3] append([1], Tail, [1,2,3]). % Tail = [2,3] append(head, [2,3], [1,2,3]). % Head = [1] append is specified declaratively, by means of two patterns. If the query matches any of the patterns, substitutions are made and either a solution is suggested, or the search loops. If the query does not match any pattern (or if previously found solutions were rejected by the user), failure is reported.
7 Relational Programming contd Example (Relational Append with or) code/append-or.oz proc {Append List1 List2 List3} or List1 = nil List2 = List3 [] Head Tail1 Tail3 in List1 = Head Tail1 List3 = Head Tail3 {Append Tail1 List2 Tail3} end end The operator or 3 is used to specify alternative computations, each performed within its own computation space. The alternative bindings of List1 (to nil or to Head Tail1) are done within two separate spaces, and are not visible to each other. When one of the computations succeeds, the binding is merged ( imported ) into the enclosing computation space. 3 Note, unlike in many other languages, or is not a logical operator (in Oz, orelse is).
8 Relational Programming contd Example (Relational Append with or contd) {Browse {Append [1] [2 3] $}} % prints [1 2 3] {Browse {Append [1] $ [1 2 3]}} % prints [2 3] {Browse {Append $ [2 3] [1 2 3]}} % prints [1] The or-based Append behaves the relational way. Try it! Execute append-test.oz (try append.pl as well). Note: The operator or is not explained in the book, and is not explained in CTMCP. or is out of pensum!
9 Relational Programming contd We can have still more fun with the Prolog append. Example (append, Prolog) consult(append). findall(solution(list1, List2), append(list1, List2, [1,2,3]), Solutions). findall will find all solutions to a query. The query is append(list1, List2, [1,2,3]), and asks for two lists that, when appended, match [1,2,3]. Each solution is reported in the form solution(list1, List2). Solutions is a list of all solutions.
10 Relational Programming contd In Oz, we can t do that with or-based Append, because or succeeds if at most one alternative succeeds. But we can do it with the non-deterministic choice statement choice. Example (Relational Append with choice) code/append-choice.oz proc {Append List1 List2 List3} choice List1 = nil List2 = List3 [] Head Tail1 Tail3 in List1 = Head Tail1 List3 = Head Tail3 {Append Tail1 List2 Tail3} end end Unlike the or-based Append, this version can report all successful computations done in separate spaces; but we need some extra functionality for this to work.
11 Relational Programming contd Example (Relational Append with choice contd) Solutions = {SolveAll fun {$} List1 List2 in {Append List1 List2 [1 2 3]} solution(list1 List2) end} SolveAll is an analogue to Prolog s findall. {Append List1 List2 [1 2 3]} is the query (with List1 and List2 explicitly declared, unlike in Prolog). solution(list1 List2) is the form in which each solution is reported. Solutions is a variable which SolveAll binds to a list of all possible solutions. Try it! Execute append-test.oz.
12 The Relational Model of Computation The relational model of computation covered in Ch. 9 is an extension of the declarative sequential model of computation from Ch. 2 with: non-deterministic choice statements, failure statements. We introduce new syntax, but explain it only with handwaving semantics. The relational model of computation is based on the broader model of computation used in constraint propagation programming. The constraint-based model of computation is explained in Ch. 12 in CTMCP, and is out of pensum. You need a rough, intuitive understanding of the relational model, with no details on how computation spaces are created and used.
13 The Relational Model of Computation contd The syntax of the kernel language is extended as follows. The choice and fail statements statement ::= choice statement { [] statement } end statement ::= fail choice sets a point of non-deterministic choice between a number of possible execution paths. A choice statement freezes the current thread; results from the child computation spaces are examined and collected by a search engine. If fail is executed by any thread in a computation space, the computation in that space fails (a unification failure has the same effect).
14 The Relational Model of Computation contd To execute a program containing a choice statement, the code has to be wrapped into a no-parameter function, and passed as an argument to a one-parameter function implementing a search strategy. Chapter 12 in CTMCP describes a depth-first search strategy, implemented in the function Solve. 4 Solve takes as input a no-parameter function that specifies the problem to be solved. Solve returns a lazy list of solutions; laziness is essential here, because a problem may, in general, have an infinite number of different solutions. The convenience function SolveOne calls Solve and forces the head of the solutions list; it then returns the first solution found by Solve. The convenience function SolveAll calls Solve and forces the entire solutions list; its output is the forced list of all solutions. 4 Solve is implemented in the file solve.oz included in the code directory for this lecture.
15 Programming with choice and Solve We can use choice to implement a function that non-deterministically returns 5 a single digit. Example (Picking a digit) code/digit.oz fun {Digit} choice 0 [] 1 [] 2 [] 3 [] 4 [] 5 [] 6 [] 7 [] 8 [] 9 end end {Browse {SolveOne Digit} % prints [0] {Browse {SolveAll Digit} % prints [ ] The function Digit is trivial, but such functions will be useful when we implement more complicated stuff, e.g., a parser. 5 When executed inside a program passed to a search engine. Non-deterministically in the sense that the order in which different values are returned is not, in principle, fixed within the function, but rather depends on the actual implementation.
16 Programming with choice and Solve A similar program could easily be written in Prolog. Example (Picking a digit, Prolog) code/digit.pl digit(0). digit(1). digit(2). digit(3). digit(4). digit(5). digit(6). digit(7). digit(8). digit(9). consult(digit). findall(digit, digit(digit), Digits). % Digits = [0,1,2,3,...]
17 Programming with choice and Solve contd Digit is specialized: it returns a digit. But its domain is handcoded in the body of the function; it would be nice to parameterize it away. Example (Generic non-deterministic pick) code/pick.oz fun {Pick List} Head Tail = List in choice Head [] {Pick Tail} end end fun {Digit} {Pick {Enumerate 0 9}} end {Browse {SolveAll Digit} % prints [ ] Given a list, Pick unifies the list with two unbound variables wrapped into a record. If the unification fail, Pick is done (no solution can be produced). Otherwise, Pick chooses between the header of the list and a value recursively picked from the tail.
18 Programming with choice and Solve contd Again, this is easy to do in Prolog. Example (Generic non-deterministic pick, Prolog) code/pick.pl pick(head, [Head Tail]). pick(item, [_ Tail]) :- pick(item, Tail). digit(digit) :- pick(digit, [0,1,2,3,4,5,6,7,8,9]). findall(digit, digit(digit), Digits). % Digits = [0,1,2,3,...] Given a variable Item and a list [Head Tail], pick either unifies Item with Head or recursively unifies it with some other element of the list. digit unifies a variable with whatever pick picks from the list of digits.
19 Programming with choice and Solve contd We can use Digit (and Pick) for some more interesting tasks. Example (Pairs of one-digit numbers summing up to 10) code/ten.oz fun {Ten} N#M = {Digit}#{Digit} in N + M = 10 ten(n M) end {Browse {SolveAll Ten}} % prints [ten(1 9) ten(2 8) ten(3 7)...] The function Ten calls {Digit} twice to pick two arbitrary one-digit integers, unifies the sum of these with 10, returns the integers wrapped into a record if the unification succeeds. Try it! Execute ten-test.oz.
20 Programming with choice and Solve contd Consider the following problem of computing change: given a finite set N of coin nominals n m, m = N, find all possible ways to give change for a specific amount a of money, using as many coins as you like. Example (Computing change) nominals: amount: change: nickel (5 cents), dime (10 cents), quarter (25 cents) 25 cents 5 nickels 3 nickels and 1 dime 1 nickel and 2 dimes 1 quarter
21 Programming with choice and Solve contd Example (Computing change) code/change.oz fun {Change Amount Purse} if Amount > 0 then Coin = {Purse} Rest = {Change Amount-Coin Purse} in {Sum Rest} + Coin = Amount Coin Rest else nil end end The function Change takes an amount to be changed and a coin generator; if the amount is not positive, returns an empty list (no-coin change or change impossible); otherwise, picks one coin, computes the change for the rest of the amount, asserts that the coin and the rest of the change add up to the amount, and returns the coin together with the rest.
22 Programming with choice and Solve contd Example (Computing change, alternative) code/change-alternative.oz fun {Change Amount Purse} choice Amount = 0 nil [] Amount > 0 = true Coin = {Purse} Rest = {Change Amount-Coin Purse} in Coin Rest end end The alternative version of Change makes two choices: the amount is positive, and given a coin it is possible to change the rest; the coin is then returned together with the rest of the change; the amount is zero; the change is no coins. If the amount is negative, the branch of the search simply fails (change impossible).
23 Programming with choice and Solve contd Example (Computing change contd) Nickel = 5 Dime = 10 Quarter = 25 fun {Purse} {Pick [Nickel Dime Quarter]} end {Browse {SolveAll fun {$} {Change Quarter Purse} end}} The two versions of Change give identical results, but the results list is redundant; some of its elements represent the same change, they just differ in the order of coin nominals: [[ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ]] Try it! Execute change-test.oz.
24 Programming with choice and Solve contd Example (Computing change, search space) [] [5] [10] [5 5] [5 10] [10 5] [10 10] [5 5 5] [5 5 10] [5 10 5] [ ] [10 5 5] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] The search is redundant, because after having chosen the second nominal, we can choose the first one again. If many more nominals were available, the search space would be exponentially larger. 6 6 There are more nodes examined than visible here; only nodes on successful paths are shown.
25 Programming with choice and Solve contd We can prevent the redundance by demanding that a nominal that has been skipped over in a search branch can never be chosen again. Example (Non-redundant change computation) code/change-nonredundant.oz fun {Change Amount Nominals} choice Amount = 0 nil [] Amount > 0 = true Coin Coins = Nominals in choice Rest = {Change Amount-Coin Nominals} in Coin Rest [] {Change Amount Coins} end end end Note: Unlike in the case where Purse were used, if the first nominal on the list is not used, the recursive call uses only the remaining nominals (second option in the internal choice). Try it! Execute change-test.oz.
26 Programming with choice and Solve contd Example (Non-redundant change, search space) [] [5] [5 5] [5 10] [5 5 5] [ ] [ ] [ ] [ ] The search is no longer redundant, because after having chosen the second nominal, we cannot choose the first one any more.
27 Search Strategies The Solve we have used so far implements the depth-first search strategy. Whenever a node does not correspond to a final solutions, further choices are made, and the node s children are examined before the node s siblings. Depth-first search is the default strategy built-in into a Prolog interpreter (there are ways to make Prolog perform, e.g., breadth-first search). The relational model of computation in Oz uses depth-first seach, but it s just because Solve is implemented this way. It is possible to reimplement Solve so that it uses, e.g., breadth-first search, or even allows the user to choose the strategy when Solve is called.
28 Search Strategies contd Example (Non-redundant change, depth-first search) [] 1: [5] 2: [5 5] 7: [5 10] 3: [5 5 5] 8: [ ] 4: [ ] 6: [ ] 5: [ ] Complete solutions are found at nodes 5, 6, and 8, in this order.
29 Search Strategies contd Example (Non-redundant change, breadth-first search) [] 1: [5] 2: [5 5] 3: [5 10] 4: [5 5 5] 5: [ ] 6: [ ] 7: [ ] 8: [ ] Complete solutions are found at nodes 5, 7, and 8, in this order.
30 Search Strategies contd The reimplemented Solve takes an additional argument, which is a flag denoting the strategy to be used. Example (Computing change, depth- or breadth-first) {Browse {SolveAll depth fun {$} {Change Quarter Nominals]} end}} {Browse {SolveAll breadth fun {$} {Change Quarter Nominals]} end}} Depth-first search: [[ ] [ ] [ ]]. Breadth-first search: [[ ] [ ] [ ]]. 7 7 For some reason the implementation of Solve used for demonstration reverses the order of the last two solutions; the implementation is taken from wiki/index.php/courses/cs 460/Fall 2005/SolveAll.
31 Relational Parsing One of the principal motivations for the development of Prolog was to be able to build parsers for artificial and natural languages by specifying the parse rules in a declarative rather than imperative way. The syntax (macrosyntax, as opposed to microsyntax, the lexical structure of lexemes) of a language is typically specified using a grammar. The idea is to write programs that closely resemble grammars in their structure (up to syntactic details of the notation), and have an interpreter use such programs to parse lists of tokens obtained from a tokenizer.
32 Relational Parsing contd A parser takes as input a linear sequence of tokens (classified lexemes), and returns, in general, a non-linear branching structure, the parse tree. We shall develop a simple syntax checker for a small subset of the Scheme programming language. A syntax checker is a stripped-down version of a parser; it takes as input a sequence of tokens, and checks whether the sequence is valid according to the grammar, i.e., whether it is parsable. Instead of a parse tree, a syntax checker returns true for syntactically valid tokens sequences, and false for invalid ones.
33 Relational Parsing contd Example (Grammar for a subset of Scheme) program ::= { instruction } instruction ::= variable definition function definition expression variable definition ::= ( DEFINE identifier expression ) function definition ::= ( DEFINE ( identifier identifier ) expression ) expression ::= identifier number application identifier ::= ID(λ) number ::= NUM(λ) application ::= ( identifier expression ) DEFINE, ID, and NUM are token class indicators. Tokens of the latter two classes are reported (by the tokenizer) together with the corresponding lexemes (λ).
34 Relational Parsing contd We can represent tokens as records and atoms (no-content records), and programs as lists of records. Example (Tokenized programs) (define a 1) is tokenized to [ ( define id( a ) num(1) ) ] (define (f x) x) is tokenized to [ ( define ( id( f ) id( x ) ) id( x ) ) ] (define (g x) (f (f x))) is tokenized to [ ( define ( id( g ) id( x ) ) ( id( f ) ( id( f ) id( x ) ) ) ) ]
35 Relational Parsing contd For each rule in the grammar, we implement a procedure (or function) that takes as input a sequence of tokens, tries to parse from the sequence a construct corresponding to the rule it implements, and returns the remaining tokens on success, and fails otherwise. Example (Parsing an identifier) proc {Identifier Tokens Rest} Tokens = id(_) Rest end Identifier unifies the head of Tokens with an identifier record (ignoring the lexeme), and unifies Rest with the tail of Tokens.
36 Relational Parsing contd Example (Parsing an expression) fun {Expression Tokens} choice {Identifier Tokens} [] {Number Tokens} [] {Application Tokens} end end Expression non-deterministically tries to parse an identifier, a number, or an application construct from Tokens, and returns the remaining tokens received from any of the nested calls.
37 Relational Parsing contd Example (Parsing variable definitions) fun {VariableDefinition Tokens} Rest in Tokens = ( define Rest {Expression {Identifier Rest} ) $} end VariableDefinition unifies the first two tokens in Tokens with ( and define, parses an identifier from the remaning tokens, parses an expression from what Identifier returns, and parses ) from what Expression returns and returns the remaining tokens.
38 Relational Parsing contd Example (Parsing function definitions) fun {FunctionDefinition Tokens} Rest in Tokens = ( define ( Rest {Expression {Identifier {Identifier Rest} ) $} ) $} end FunctionDefinition works like VariableDefinition, just that the parsed construct is more complex.
39 Relational Parsing contd Example (Parsing sequences of tokens) fun {Sequence Tokens} choice Tokens = nil nil [] {Sequence {Instruction Tokens}} end end Sequence non-deterministically choses between Tokens being an empty list and Tokens being a list containing an instruction possibly followed by further tokens.
40 Relational Parsing contd Example (Parsing programs) fun {Check Tokens} fun {Sequence}... end fun {Instruction}... end... in {SolveAll fun {$} {Sequence Tokens nil} true end} \= nil end Check uses SolveAll to find all solutions to the parse problem, and returns true if the solutions list is non-empty. The function passed to SolveAll succeeds if Tokens can be parsed as a valid program with no trailing tokens; on success, true is returned. 8 8 Any other value could be used; in particular, it could be a parse tree.
41 Relational Parsing contd Try it! Execute checker-test.oz. Try it! Examine parser.oz and execute parser-test.oz to see how to easily extend the code to have a parser (which returns a list of parse trees) rather than a checker (which returns just true or false).
42 Automated Translation? From the Bible, Matthew 26:41: The spirit is willing, but the flesh is weak. From an automated English to Russian to English military translation machine: The vodka is good, but the meat is rotten. Note: Parsing is not all.
43 Lecture Outline Relational Programming contd The Relational Model of Computation Programming with choice and Solve Search Strategies Relational Parsing Summary
44 Summary This time Next time Homework Pensum Further reading Relational programming. Object oriented programming. Reading Secc in CTMCP. You should have a rough understanding of today s material, without details of non-oz code. Sterling and Shapiro The Art of Prolog
Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011
Lecture 5: Declarative Programming. The Declarative Kernel Language Machine September 12th, 2011 1 Lecture Outline Declarative Programming contd Dataflow Variables contd Expressions and Statements Functions
More informationLecture 6: The Declarative Kernel Language Machine. September 13th, 2011
Lecture 6: The Declarative Kernel Language Machine September 13th, 2011 Lecture Outline Computations contd Execution of Non-Freezable Statements on the Abstract Machine The skip Statement The Sequential
More informationLecture 4: The Declarative Sequential Kernel Language. September 5th 2011
Lecture 4: The Declarative Sequential Kernel Language September 5th 2011 1 Lecture Outline Syntactic Analysis of Programs contd Scanning contd The Declarative Kernel Language Introduction Syntax of the
More informationImplementação de Linguagens 2016/2017
Implementação de Linguagens Ricardo Rocha DCC-FCUP, Universidade do Porto ricroc @ dcc.fc.up.pt Ricardo Rocha DCC-FCUP 1 Logic Programming Logic programming languages, together with functional programming
More informationAn Oz Subset. 1 Microsyntax for An Oz Subset. Notational Conventions. COP 4020 Programming Languages 1 January 17, 2012
COP 4020 Programming Languages 1 January 17, 2012 An Oz Subset This document describes a subset of Oz [VH04] that is designed to be slightly larger than the declarative kernel language of chapter 2 (of
More informationDon t write anything in the field marked Eventuell ekstra ID. For each subtask, choose the answer you think is the most correct one.
Contact persons under the exam: Per Holager, tlf 99 61 78 36 Ole Edsberg tlf 95 28 15 86 Language: English EXAM IN COURSE TDT4165 PROGRAMMING LANGUAGES Saturday May 15th, 2004, 0900 1300 No printed or
More information1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.
1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered
More informationCS164: Midterm I. Fall 2003
CS164: Midterm I Fall 2003 Please read all instructions (including these) carefully. Write your name, login, and circle the time of your section. Read each question carefully and think about what s being
More informationProgramming Language Concepts, cs2104 Lecture 04 ( )
Programming Language Concepts, cs2104 Lecture 04 (2003-08-29) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-09-05 S. Haridi, CS2104, L04 (slides: C. Schulte, S. Haridi) 1
More informationSpecial Directions for this Test
1 Fall, 2007 Name: COP 4020 Programming Languages 1 Makeup Test on Declarative Programming Techniques Special Directions for this Test This test has 8 questions and pages numbered 1 through 9. This test
More informationSemantic Analysis. Lecture 9. February 7, 2018
Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average
More informationLecture 8: Recursion and Iteration. Exceptions. Declarative Programming.
Lecture 8: Recursion and Iteration. Exceptions. Declarative Programming. September 26th, 2010 Lecture 8: Recursion and Iteration. Exceptions. Declarative Programming. (1/48) Lecture Outline Memory Management,
More informationFormal Semantics. Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1
Formal Semantics Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1 Formal Semantics At the beginning of the book we saw formal definitions of syntax with BNF And how to make a BNF that generates
More informationProgramming Languages Third Edition
Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand
More informationTail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))
Tail Recursion 1 Tail Recursion In place of loops, in a functional language one employs recursive definitions of functions. It is often easy to write such definitions, given a problem statement. Unfortunately,
More information2.2 Syntax Definition
42 CHAPTER 2. A SIMPLE SYNTAX-DIRECTED TRANSLATOR sequence of "three-address" instructions; a more complete example appears in Fig. 2.2. This form of intermediate code takes its name from instructions
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 informationMIT Top-Down Parsing. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology
MIT 6.035 Top-Down Parsing Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Orientation Language specification Lexical structure regular expressions Syntactic structure
More informationCSE341 Autumn 2017, Final Examination December 12, 2017
CSE341 Autumn 2017, Final Examination December 12, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please
More informationSyntactic Analysis. CS345H: Programming Languages. Lecture 3: Lexical Analysis. Outline. Lexical Analysis. What is a Token? Tokens
Syntactic Analysis CS45H: Programming Languages Lecture : Lexical Analysis Thomas Dillig Main Question: How to give structure to strings Analogy: Understanding an English sentence First, we separate a
More informationDeclarative Computation Model
Declarative Computation Model Kernel language semantics revisited (VRH 2.4.5) From kernel to practical language (VRH 2.6) Exceptions (VRH 2.7) Carlos Varela RPI March 19, 2012 Adapted with permission from:
More informationProgram Abstractions, Language Paradigms. CS152. Chris Pollett. Aug. 27, 2008.
Program Abstractions, Language Paradigms. CS152. Chris Pollett. Aug. 27, 2008. Outline. Abstractions for telling a computer how to do things. Computational Paradigms. Language Definition, Translation.
More informationA Simple Syntax-Directed Translator
Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far
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 Statically vs. Dynamically typed languages
More informationHard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.
CS 3110 Spring 2015 Problem Set 3 Version 0 (last modified March 12, 2015) Soft deadline: 3/26/15 11:59pm Hard deadline: 3/28/15 1:00pm Overview In this assignment you will implement several functions
More informationWorking with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).
Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in
More informationFunctional programming with Common Lisp
Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions
More informationProgramming Language Concepts, cs2104 Lecture 09 ( )
Programming Language Concepts, cs2104 Lecture 09 (2003-10-10) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-10-03 S. Haridi, CS2104, L09 (slides: C. Schulte, S. Haridi) 1
More informationLogic Programming (CTM ) Constraint Programming: Constraints and Computation Spaces
Logic Programming (CTM 12.3-12.5) Constraint Programming: Constraints and Computation Spaces Carlos Varela Rennselaer Polytechnic Institute December 4, 2015 C. Varela 1 Generate and Test Example We can
More informationCSE341 Spring 2017, Final Examination June 8, 2017
CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please
More informationLexical Analysis. Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast!
Lexical Analysis Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast! Compiler Passes Analysis of input program (front-end) character stream
More informationLexical and Syntax Analysis. Top-Down Parsing
Lexical and Syntax Analysis Top-Down Parsing Easy for humans to write and understand String of characters Lexemes identified String of tokens Easy for programs to transform Data structure Syntax A syntax
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 informationIn Our Last Exciting Episode
In Our Last Exciting Episode #1 Lessons From Model Checking To find bugs, we need specifications What are some good specifications? To convert a program into a model, we need predicates/invariants and
More informationData Types The ML Type System
7 Data Types 7.2.4 The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE 7.96 1. fun fib (n) = 2. let
More informationTopic B: Backtracking and Lists
Topic B: Backtracking and Lists 1 Recommended Exercises and Readings From Programming in Prolog (5 th Ed.) Readings: Chapter 3 2 Searching for the Answer In order for a Prolog program to report the correct
More informationMIDTERM EXAM (Solutions)
MIDTERM EXAM (Solutions) Total Score: 100, Max. Score: 83, Min. Score: 26, Avg. Score: 57.3 1. (10 pts.) List all major categories of programming languages, outline their definitive characteristics and
More informationPrinciples of Programming Languages COMP251: Syntax and Grammars
Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2006
More informationLecture 2: SML Basics
15-150 Lecture 2: SML Basics Lecture by Dan Licata January 19, 2012 I d like to start off by talking about someone named Alfred North Whitehead. With someone named Bertrand Russell, Whitehead wrote Principia
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 informationCSE341 Spring 2017, Final Examination June 8, 2017
CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please
More informationML 4 A Lexer for OCaml s Type System
ML 4 A Lexer for OCaml s Type System CS 421 Fall 2017 Revision 1.0 Assigned October 26, 2017 Due November 2, 2017 Extension November 4, 2017 1 Change Log 1.0 Initial Release. 2 Overview To complete this
More informationLecture Notes on Program Equivalence
Lecture Notes on Program Equivalence 15-312: Foundations of Programming Languages Frank Pfenning Lecture 24 November 30, 2004 When are two programs equal? Without much reflection one might say that two
More informationCMSC 330: Organization of Programming Languages. Operational Semantics
CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged
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 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 informationIntroduction to Lexical Analysis
Introduction to Lexical Analysis Outline Informal sketch of lexical analysis Identifies tokens in input string Issues in lexical analysis Lookahead Ambiguities Specifying lexical analyzers (lexers) Regular
More informationRacket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.
Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 3 September 5, 2018 Value-Oriented Programming (continued) Lists and Recursion CIS 120 Announcements Homework 1: OCaml Finger Exercises Due: Tuesday
More informationAbstract Syntax Trees & Top-Down Parsing
Abstract Syntax Trees & Top-Down Parsing Review of Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree
More informationAbstract Syntax Trees & Top-Down Parsing
Review of Parsing Abstract Syntax Trees & Top-Down Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree
More informationWorking with recursion
Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in
More informationlci Manual Kostas Chatzikokolakis 12 March 2006
lci Manual Kostas Chatzikokolakis 12 March 2006 This manual describes the use of lci, which is an advanced interpreter for the λ-calculus. This program was first developed by Kostas Chatzikokolakis as
More informationLexical Analysis. Dragon Book Chapter 3 Formal Languages Regular Expressions Finite Automata Theory Lexical Analysis using Automata
Lexical Analysis Dragon Book Chapter 3 Formal Languages Regular Expressions Finite Automata Theory Lexical Analysis using Automata Phase Ordering of Front-Ends Lexical analysis (lexer) Break input string
More informationProcessing lists in Prolog - 2
Processing lists in Prolog - 2 This lecture shows that techniques introduced before (analysing terminating conditions and recursive programming) can be used to develop more complex procedures. This lecture
More information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More informationOn Academic Dishonesty. Declarative Computation Model. Single assignment store. Single assignment store (2) Single assignment store (3)
Declarative Computation Model Single assignment store (VRH 2.2) Kernel language syntax (VRH 2.3) Carlos Varela RPI October 6, 2009 Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL On Academic
More informationCompiler Construction
Compiled on 5/05/207 at 3:2pm Abbreviations NFA. Non-deterministic finite automaton DFA. Deterministic finite automaton Compiler Construction Collection of exercises Version May 5, 207 General Remarks
More informationCS Lecture 2. The Front End. Lecture 2 Lexical Analysis
CS 1622 Lecture 2 Lexical Analysis CS 1622 Lecture 2 1 Lecture 2 Review of last lecture and finish up overview The first compiler phase: lexical analysis Reading: Chapter 2 in text (by 1/18) CS 1622 Lecture
More informationNotes on Higher Order Programming in Scheme. by Alexander Stepanov
by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of
More informationA simple syntax-directed
Syntax-directed is a grammaroriented compiling technique Programming languages: Syntax: what its programs look like? Semantic: what its programs mean? 1 A simple syntax-directed Lexical Syntax Character
More informationIntroduction to Parsing. Lecture 8
Introduction to Parsing Lecture 8 Adapted from slides by G. Necula Outline Limitations of regular languages Parser overview Context-free grammars (CFG s) Derivations Languages and Automata Formal languages
More informationCOMPUTER SCIENCE TRIPOS
CST.2011.3.1 COMPUTER SCIENCE TRIPOS Part IB Monday 6 June 2011 1.30 to 4.30 COMPUTER SCIENCE Paper 3 Answer five questions. Submit the answers in five separate bundles, each with its own cover sheet.
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 informationCOSC252: Programming Languages: Semantic Specification. Jeremy Bolton, PhD Adjunct Professor
COSC252: Programming Languages: Semantic Specification Jeremy Bolton, PhD Adjunct Professor Outline I. What happens after syntactic analysis (parsing)? II. Attribute Grammars: bridging the gap III. Semantic
More informationOperational Semantics. One-Slide Summary. Lecture Outline
Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:
More informationIntroduction to Prolog Paper Refs. Prolog tutor. Julian Verdurmen. Seminar Softw. tech. for teaching and learning. September 30, 2009
Seminar Softw. tech. for teaching and learning September 30, 2009 Outline 1 Introduction to Prolog Basics Simple example 2 Basics Simple example Outline 1 Introduction to Prolog Basics Simple example 2
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
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 informationCOMP 181 Compilers. Administrative. Last time. Prelude. Compilation strategy. Translation strategy. Lecture 2 Overview
COMP 181 Compilers Lecture 2 Overview September 7, 2006 Administrative Book? Hopefully: Compilers by Aho, Lam, Sethi, Ullman Mailing list Handouts? Programming assignments For next time, write a hello,
More informationDeclarative Concurrency (CTM 4)
Declarative Concurrency (CTM 4) Carlos Varela Rensselaer Polytechnic Institute Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL November 21, 2014 C. Varela; Adapted with permission from
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2010 P. N. Hilfinger CS 164: Final Examination (revised) Name: Login: You have
More informationCompiler Construction
Compiler Construction Collection of exercises Version February 7, 26 Abbreviations NFA. Non-deterministic finite automaton DFA. Deterministic finite automaton Lexical analysis. Construct deterministic
More informationParser Tools: lex and yacc-style Parsing
Parser Tools: lex and yacc-style Parsing Version 6.11.0.6 Scott Owens January 6, 2018 This documentation assumes familiarity with lex and yacc style lexer and parser generators. 1 Contents 1 Lexers 3 1.1
More informationDiscussion 11. Streams
Discussion 11 Streams 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 books, so I will not dwell
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
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 informationRecursion, Structures, and Lists
Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 4 04/10/04 30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists 1 The central ideas of Prolog
More informationFaculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology
Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4020 July 5, 2007 14.00-15.30 This exam (8 pages) consists of 60 True/False
More informationTail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)
CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)
More informationSEMANTIC ANALYSIS TYPES AND DECLARATIONS
SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether
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 Compilers with Phoenix
Building Compilers with Phoenix Syntax-Directed Translation Structure of a Compiler Character Stream Intermediate Representation Lexical Analyzer Machine-Independent Optimizer token stream Intermediate
More informationContents. Chapter 1 SPECIFYING SYNTAX 1
Contents Chapter 1 SPECIFYING SYNTAX 1 1.1 GRAMMARS AND BNF 2 Context-Free Grammars 4 Context-Sensitive Grammars 8 Exercises 8 1.2 THE PROGRAMMING LANGUAGE WREN 10 Ambiguity 12 Context Constraints in Wren
More informationLecture 2: Big-Step Semantics
Lecture 2: Big-Step Semantics 1 Representing Abstract Syntax These are examples of arithmetic expressions: 2 * 4 1 + 2 + 3 5 * 4 * 2 1 + 2 * 3 We all know how to evaluate these expressions in our heads.
More informationParsing II Top-down parsing. Comp 412
COMP 412 FALL 2018 Parsing II Top-down parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled
More informationSyntax-Directed Translation. Lecture 14
Syntax-Directed Translation Lecture 14 (adapted from slides by R. Bodik) 9/27/2006 Prof. Hilfinger, Lecture 14 1 Motivation: parser as a translator syntax-directed translation stream of tokens parser ASTs,
More informationn n Try tutorial on front page to get started! n spring13/ n Stack Overflow!
Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!
More informationSemantics. A. Demers Jan This material is primarily from Ch. 2 of the text. We present an imperative
CS411 Notes 1: IMP and Large Step Operational Semantics A. Demers 23-25 Jan 2001 This material is primarily from Ch. 2 of the text. We present an imperative language called IMP; wegive a formal definition
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 informationCompilers - Chapter 2: An introduction to syntax analysis (and a complete toy compiler)
Compilers - Chapter 2: An introduction to syntax analysis (and a complete toy compiler) Lecturers: Paul Kelly (phjk@doc.ic.ac.uk) Office: room 304, William Penney Building Naranker Dulay (nd@doc.ic.ac.uk)
More informationSMURF Language Reference Manual Serial MUsic Represented as Functions
SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu
More informationMidterm II CS164, Spring 2006
Midterm II CS164, Spring 2006 April 11, 2006 Please read all instructions (including these) carefully. Write your name, login, SID, and circle the section time. There are 10 pages in this exam and 4 questions,
More informationProgramming Paradigms
PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE
More informationCS422 - Programming Language Design
1 CS422 - Programming Language Design Elements of Functional Programming Grigore Roşu Department of Computer Science University of Illinois at Urbana-Champaign 2 The two languages that we defined so far
More informationLexical and Syntax Analysis
Lexical and Syntax Analysis (of Programming Languages) Top-Down Parsing Lexical and Syntax Analysis (of Programming Languages) Top-Down Parsing Easy for humans to write and understand String of characters
More informationCompiler Design Concepts. Syntax Analysis
Compiler Design Concepts Syntax Analysis Introduction First task is to break up the text into meaningful words called tokens. newval=oldval+12 id = id + num Token Stream Lexical Analysis Source Code (High
More informationA programming language requires two major definitions A simple one pass compiler
A programming language requires two major definitions A simple one pass compiler [Syntax: what the language looks like A context-free grammar written in BNF (Backus-Naur Form) usually suffices. [Semantics:
More informationLecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
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 information