COMPUTER SCIENCE TRIPOS

Similar documents
COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

COMPUTER SCIENCE TRIPOS

CSCI-GA Scripting Languages

COMPUTER SCIENCE TRIPOS

A Small Interpreted Language

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

CS558 Programming Languages

Chapter 15. Functional Programming Languages

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

COMPUTER SCIENCE TRIPOS

G Programming Languages - Fall 2012

CPS 506 Comparative Programming Languages. Programming Language Paradigm

Topic VIII. The state of the art Scala < > Scala By Example by M. Odersky. Programming Methods Laboratory, EPFL, 2008.

MIDTERM EXAMINATION - CS130 - Spring 2005

CSE3322 Programming Languages and Implementation

Documentation for LISP in BASIC

And Parallelism. Parallelism in Prolog. OR Parallelism

CSCI 3155: Homework Assignment 3

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

COMPUTER SCIENCE TRIPOS

Functional Programming. Pure Functional Programming

COMPUTER SCIENCE TRIPOS Part II (General) DIPLOMA IN COMPUTER SCIENCE

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

1 Lexical Considerations

Functional Programming. Pure Functional Languages

Lists. Michael P. Fourman. February 2, 2010

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS 3360 Design and Implementation of Programming Languages. Exam 1

CSCI 3155: Homework Assignment 4

Exercise 1: Graph coloring (10 points)

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Introduction to Programming Using Java (98-388)

COMPUTER SCIENCE TRIPOS Part II (General) DIPLOMA IN COMPUTER SCIENCE

COMPUTER SCIENCE TRIPOS

The Typed Racket Guide

Typed Racket: Racket with Static Types

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

An introduction introduction to functional functional programming programming using usin Haskell

Semester Review CSC 301

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

CPSC 311, 2010W1 Midterm Exam #2

Formal Semantics. Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1

The role of semantic analysis in a compiler

Types and Type Inference

Functional Programming. Big Picture. Design of Programming Languages

CS143 Final Fall 2009

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring Instructions:

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Computing Science 114 Solutions to Midterm Examination Tuesday October 19, In Questions 1 20, Circle EXACTLY ONE choice as the best answer

Functional Programming. Pure Functional Languages

Problems and Solutions to the January 1994 Core Examination

syntax tree - * * * - * * * * * 2 1 * * 2 * (2 * 1) - (1 + 0)

UNIVERSITETET I OSLO

Programming Languages Third Edition

CS3360 Design and Implementation of Programming Languages Final Exam May 16, pm to 12:45pm (2 hour and 40 minutes) NAME:

Note that pcall can be implemented using futures. That is, instead of. we can use

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

In Our Last Exciting Episode

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

More Examples. Lecture 24: More Scala. Higher-Order Functions. Control Structures

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

Semantic Analysis and Type Checking

CSCI-GA Final Exam

COMPUTER SCIENCE TRIPOS

Programming Languages, Summary CSC419; Odelia Schwartz

NOTE: Answer ANY FOUR of the following 6 sections:

Operational Semantics. One-Slide Summary. Lecture Outline

COMPUTER SCIENCE TRIPOS

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Denotational semantics

Type Systems, Type Inference, and Polymorphism

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

CS450 - Structure of Higher Level Languages

15 Unification and Embedded Languages in Lisp

Example Scheme Function: equal

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

MIDTERM EXAM (Solutions)

CA Compiler Construction

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

Object typing and subtypes

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Informatica 3 Syntax and Semantics

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

So what does studying PL buy me?

Transcription:

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. On each cover sheet, write the numbers of all attempted questions, and circle the number of the question attached. You may not start to read the questions printed on the subsequent pages of this question paper until instructed that you may do so by the Invigilator STATIONERY REQUIREMENTS Script paper Blue cover sheets Tags SPECIAL REQUIREMENTS Approved calculator permitted

CST.2011.3.2 1 Algorithms II The pseudocode below is a first attempt at a recursive algorithm to enumerate all the paths from source to sink, in the context of a maximum flow problem. 0 def allpaths(graph, source, sink): 1 # Each path is a list of vertices from source to sink, eg [2, 4, 7] 2 # The result is a list of paths, eg [[2, 4, 7], [2, 7]], initially empty 3 result = [] 4 5 if source == sink: 6 result.append([source]) 7 else: 8 for v in graph.verticesadjacentto(source): 9 for path in allpaths(graph, v, sink): 10 # Reject paths that revisit the source, else infinite loops 11 if source not in path: 12 result.append([source] + path) 13 return result (a) Point out all the bugs you can find, highlighting the failures with test cases. Correct all the bugs you found, clearly explaining your fixes. Rewrite a corrected and clearly commented version of the pseudocode. [10 marks] Provide a correctness proof for your new version. 2

CST.2011.3.3 2 Algorithms II (a) Explain, with prose and no more than 15 lines of pseudocode, the Jarvis s march algorithm for finding the convex hull of a set of points. Marks awarded for: clarity of explanation, legibility of pseudocode, correctness of algorithm. Consider the following claim: The cross-product trick can be used as a plug-in substitution for the comparison operation between two arguments that gives a three-way result (namely <, > or =). Therefore, given an arbitrary set of 2D vectors all starting from the origin, I can sort them in order of increasing polar angle, from 0 to 2π, without computing any angles, merely by applying a standard sort algorithm with the comparison operation replaced by the crossproduct trick. (i) Explain the cross-product trick. [3 marks] (ii) Prove the correctness of the above claim or refute it with a clearly explained graphical or numerical counterexample. [7 marks] Traditionally, Jarvis s march handles the left side and the right side of the hull separately. Clearly explain why a single pass would not work as desired and then describe a variant implementation to handle the problem in one pass, highlighting its advantages and disadvantages. [Hint: see part (ii).] 3 (TURN OVER)

CST.2011.3.4 3 Programming in C and C++ In this question, where appropriate, you may use a short fragment of code to complement your explanation. (a) What is the difference between declaration and definition? Describe the layout of the memory components: Dynamic Memory Allocation, Data Segment, Code Segment and Stack. You may use an illustration as part of your explanation. Using an example, explain what stack unwinding is in C++. (d) How may I use template meta programming to inline recursive functions? (e) Why did the designers of the C++ language decide to make an empty class 1 byte in length? [4 marks each] 4 Compiler Construction (a) In a stack-based runtime system, what problem does the static link method attempt to solve, and how does it work? Can static linking be used to implement a language with first-class functions? If yes, then explain how. If no, give an example and explain how static linking fails. Explain how exceptions (ML-like raise and handle) could be implemented with a stack-oriented machine. (d) A program may evaluate to an exception that has been raised all the way to the top-level and never handled. Discuss how you might modify your implementation in part to dump debugging information when such toplevel exceptions are raised. The debugging information should include some description of the state of the computation just before the top-level exception was raised. 4

CST.2011.3.5 5 Compiler Construction Consider a simple grammar for arithmetic expressions: E ::= n x E E + E ( E ) with n ranging over integer constants and x ranging over variables. We want to compile expressions to code for a simple stack-based machine with the following instruction set. instruction pushvar k push n add neg meaning push the value of the k-th variable on top of stack push n on top of stack replace the top two stack items with their sum replace the top stack item with its negation For this problem, we will not worry about how variables are bound to values nor how abstract syntax trees are produced. (a) How will your compiler generate code from expressions of the form E? How will your compiler generate code from expressions of the form E 1 + E 2? What code will your compiler generate for the expression -(-x + (17 + y))? (d) Suppose we now want to extend the language of integer expressions with multiplication E ::= E E but we cannot extend the machine with an instruction for multiplication. Can you implement this extended language directly with the machine instruction set presented above? If not, suggest a minimal extension to the instruction set that allows for the implementation of multiplication using the addition from the instruction set. Explain the semantics of your extensions and how you would use them to implement multiplication. [8 marks] 5 (TURN OVER)

CST.2011.3.6 6 Concepts in Programming Languages (a) Give one difference and one similarity between the programming languages: (i) Algol and SIMULA [2 marks] (ii) LISP and Smalltalk [2 marks] What is the type of the expression fn f => fn x => f(f(x)) inferred by the SML interpreter? Explain your answer. Give an example in the SML Modules language of two distinct signatures, say IN and OUT, and of a functor that takes structures matching IN to produce structures matching OUT. (d) Comment on the mechanism for parameter-passing in the programming language Scala. You may wish to consider the following two code samples. def whileloop( cond: => Boolean )( comm: => Unit ) { if( cond ) comm; whileloop( cond )( comm ) def qsort[t]( xs: Array[T] )( implicit o: Ord[T] ): Array[T] = if( xs.length <= 1 ) xs else { val pivot = xs( xs.length/2 ) Array.concat ( qsort( xs filter (x => x.lt(x,pivot)) ), xs filter (x => x == pivot ), qsort( xs filter (x => x.lt(pivot,x)) ) ) 6

CST.2011.3.7 7 Further Java In this question you will need to fill in missing parts of a Java program. You may ignore any exception handling and will not be penalised for minor syntactic errors. You are provided with a class Eval: public class Eval { public static int f(record r) {... (a) Add another method Integer maxf(iterator<record> it) to the class Eval. Your method should return the maximum value computed by f for every Record returned by the iterator or null if there are no records available. The relevant portion of the Iterator interface is as follows: interface Iterator<T> { // return true if there are more values available public boolean hasnext(); // return the available value and advance to the next one public T next(); Complete the methods run() and join() in the following abstract class. You may add additional fields or methods if you wish. abstract class Joinable implements Runnable { abstract void exec(); final public void run() { //... call the exec() method... void join() throws InterruptedException { // block the calling thread until exec() completes in run() [7 marks] Provide a method Integer parmaxf(iterator<record> it, int n) which is functionally equivalent to Eval.maxf, except that it should create n parallel threads of execution to speed up the calculation of the result. You may assume that Iterator<Record> is thread-safe. You may find it helpful to subclass the Joinable class. [8 marks] 7 (TURN OVER)

CST.2011.3.8 8 Prolog (a) Give the result and any variable bindings that occur from making each of the following (independent) queries: (i) A=3 (ii) A is 4 (iii) A<5 (iv) A=6,not(A=6) [1 mark] [1 mark] [1 mark] [1 mark] Consider the following clauses: a(1). a(a). b(3). b(a). c(a,b) :- b(b),!,a(a). c(x,_) :- a(x),b(x). (i) List all the solutions to the query c(a,b) in order, giving any binding of variables that occurs. [2 marks] (ii) List all the solutions to the query c(x,1) in order, giving any binding of variables that occurs. [2 marks] A binary tree has nodes whose values are non-empty lists. A tree node is represented using a term that takes the form Left-SomeList+Right or nil (note that parentheses can be used to enforce precedence). For example, the following term would be a valid tree: nil-[root,1,2]+(nil-[child,4]+nil) (i) Write a predicate preorder(+tree,-valuelist) that unifies ValueList with a list containing all of the tree nodes values from a pre-order tree walk (i.e. emit node value, then left subtree, then right subtree). The predicate should fail if any of the tree nodes values are not of the correct form. For the above example tree, preorder/2 would unify ValueList with [[root,1,2],[child,4]]. You may assume that append/3 has been defined already. (ii) Now write a predicate preorderdl/2 that behaves exactly like your preorder/2 predicate, but in its implementation makes use of difference lists, instead of querying append/3. 8

CST.2011.3.9 9 Software Engineering (a) Describe the waterfall model for software development and list three of its advantages for software development. When discussing system development Fred Brooks says, plan to throw one away you will anyway. What disadvantages of the waterfall model is he referring to? Outline an alternative software development model that deals with these disadvantages. [7 marks] You work for a large social networking company which has recently introduced a one-to-one chat mechanism, promising that they will never censor conversations. Users are now reporting that their friends computers are being compromised by malicious software. When users click on links within messages sent by this malicious software, their machine is also compromised, and spreads the infection still further. A crisis meeting has decided that the chat software must be modified to block this worm behaviour. As manager of this project, how will you approach the development, how will you estimate how long the task will take, and how will you establish that your solution is safe to deploy? [8 marks] END OF PAPER 9