Final Review. COMP 524: Programming Languages Srinivas Krishnan April 25, 2011

Similar documents
Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

Binding and Storage. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

G Programming Languages - Fall 2012

CS 415 Midterm Exam Spring SOLUTION

CS 415 Midterm Exam Fall 2003


Pace University. Fundamental Concepts of CS121 1

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

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

G Programming Languages - Fall 2012

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Programming Languages Third Edition. Chapter 7 Basic Semantics

CMSC 330: Organization of Programming Languages

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

LECTURE 18. Control Flow

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

MIDTERM EXAM (Solutions)

CMSC 331 Final Exam Section 0201 December 18, 2000

TYPES, VALUES AND DECLARATIONS

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

Lecture 13: Complex Types and Garbage Collection

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

Scope, Functions, and Storage Management

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

About this exam review

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

22c:111 Programming Language Concepts. Fall Types I

CS 415 Midterm Exam Spring 2002

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

11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e

The SPL Programming Language Reference Manual

CS 480 Fall Runtime Environments. Mike Lam, Professor. (a.k.a. procedure calls and heap management)

Concepts Introduced in Chapter 7

INF 102 CONCEPTS OF PROG. LANGS FUNCTIONAL COMPOSITION. Instructors: James Jones Copyright Instructors.

G Programming Languages - Fall 2012

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

CS 314 Principles of Programming Languages

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Briefly describe the purpose of the lexical and syntax analysis phases in a compiler.

The role of semantic analysis in a compiler

CSE 307: Principles of Programming Languages

Short Notes of CS201

CIS 1.5 Course Objectives. a. Understand the concept of a program (i.e., a computer following a series of instructions)

CS201 - Introduction to Programming Glossary By

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation

Chapter 9 Subprograms

Weeks 6&7: Procedures and Parameter Passing

Final-Term Papers Solved MCQS with Reference

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Tail 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

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

CS558 Programming Languages

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM.

Control in Sequential Languages

Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008.

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers)

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

COMPUTER SCIENCE TRIPOS

Lecture08: Scope and Lexical Address

CS 360 Programming Languages Interpreters

Subprograms. Copyright 2015 Pearson. All rights reserved. 1-1

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

CS 314 Principles of Programming Languages

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization.

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

About the Authors... iii Introduction... xvii. Chapter 1: System Software... 1

Project Compiler. CS031 TA Help Session November 28, 2011

JVM ByteCode Interpreter

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Lecture 7: Binding Time and Storage

Review of the C Programming Language

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011

Operational Semantics. One-Slide Summary. Lecture Outline

Control Abstraction. Hwansoo Han

Midterm 2 Solutions Many acceptable answers; one was the following: (defparameter g1

StackVsHeap SPL/2010 SPL/20

Run-time Environments

low and not larger than high. 18 points

Operational Semantics of Cool

Semantic Analysis. Lecture 9. February 7, 2018

Run-time Environments - 3

Run-time Environments

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

CS164: Programming Assignment 5 Decaf Semantic Analysis and Code Generation

CSC 533: Organization of Programming Languages. Spring 2005

Compiler Construction D7011E

Q1: Finite State Machine (8 points)

Procedure and Object- Oriented Abstraction

Programming Language Concepts, cs2104 Lecture 04 ( )

6. Names, Scopes, and Bindings

Storage. Outline. Variables and Updating. Composite Variables. Storables Lifetime : Programming Languages. Course slides - Storage

INTRODUCTION PRINCIPLES OF PROGRAMMING LANGUAGES. Norbert Zeh Winter Dalhousie University 1/10

NOTE: Answer ANY FOUR of the following 6 sections:

COMP 524 Spring 2018 Midterm Thursday, March 1

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Chapter 9. Subprograms

Garbage Collection. Steven R. Bagley

Transcription:

Final Review COMP 524: Programming Languages Srinivas Krishnan April 25, 2011 Based in part on slides and notes by Bjoern Brandenburg, S. Olivier and A. Block. 1

Question Types Lay of the Land Simple True/False, Fill in the Blanks Problem Solving: Read a scenario and apply what you have learnt so far Theoretical Problems: Similar to midterm, there will be one asymptotic complexity question on Generational GC ;) Code: Write Snippets of Code, Read and Evaluate Code Extra Credit: Problem Solving based on class lectures 2 2

Nuts n Bolts Lay of the Land 120 Minutes, but you can take all 180 minutes if you want Closed Book Total Points: -100 Coverage: All topics since the beginning of semester, focus on topics on the latter half of the semester 3 3

Suppose you are stranded on a desert island with a computer (with an assembler and a basic OS) and need a compiler for a high-level language such as Haskell. How do you obtain one? By cross-compiling. 1) Start by modifying the existing Haskell compiler that can generate x86 machine code to also be able to generate PowerPC machine code. 2) Now, compile the modified compiler with itself to produce a compiler that runs on x86 but produces PowerPC machine code. 3) Use the compiler produced in step 2), which runs on x86 but produces PowerPC code, and compile itself again. This time, the result is a compiler that runs on PowerPC and that produces PowerPC machine code. We went from a x86->x86 compiler to a PowerPC->PowerPC compiler. 4 4

Still on the desert island. Suppose we have a working, self-hosting Haskell compiler on our rescue pod computer (an Intel x86 machine), but found a PowerPC computer in a satellite wreck, and would like to have a working, self-hosting Haskell compiler on the satellite computer. By cross-compiling. 1) Start by modifying the existing Haskell compiler that can generate x86 machine code to also be able to generate PowerPC machine code. 2) Now, compile the modified compiler with itself to produce a compiler that runs on x86 but produces PowerPC machine code. 3) Use the compiler produced in step 2), which runs on x86 but produces PowerPC code, and compile itself again. This time, the result is a compiler that runs on PowerPC and that produces PowerPC machine code. We went from a x86->x86 compiler to a PowerPC->PowerPC compiler. 5 5

What are the first two phases of a compiler? Lexical analysis and syntax analysis. 6 6

How can we recognize regular grammars? With DFAs (deterministic finite automata). 7 7

What are the four types of terms in Prolog Atoms, variables, numeric literals, and structures 8 8

Write a Prolog clause xor_equal/4 that has the following behavior: xor_equal(a, a, b, c). true. xor_equal(a, b, b, b). true. xor_equal(a, a, b, b). false. xor_equal(a, B, C, D) :- A = B, C = D,!, fail. xor_equal(a, B, _, _) :- A = B,!. xor_equal(_, _, C, D) :- C = D. 9 9

How can you do iterative computations in Prolog? Only with recursion, since there are no loops 10 10

What is the Cut Operator used for in Prolog? Control backtracking. a :- b. b :- c. c :- d. b. a(x) :- b(x), c(x),!, d(x). 11 11

Cut Operator Superfluous answer because X unified with both B and C. controlling backtracking Cut branches from the search tree. Avoid finding too many answers. E.g., answers could be symmetrical / redundant. one_of(x, A, _, _) :- X = A. one_of(x, _, B, _) :- X = B. one_of(x, _, _, C) :- X = C.?- one_of(unc, duke, unc, state). true.?- one_of(unc, duke, unc, unc). true ; true. 12 12

Cut Operator controlling backtracking one_of_cut(x, A, _, _) :- X = A,!. one_of_cut(x, _, B, _) :- X = B,!. one_of_cut(x, _, _, C) :- X = C.?- one_of(unc, duke, unc, unc). The cut (!) predicate. Written as exclamation point. Always succeeds. Side effect: discard all previously-found backtracking points. i.e., commit to the current binding of variables; don t restore. 13 13

Negation Prolog negation differs from logical negation. Otherwise not implementable. Math: (not X) is true if and only if X is false. Prolog: (not X) is true if goal X cannot be satisfied. i.e., (not X) is true if Prolog cannot find an answer for X. SWI Syntax: \+ X means not X. Can be defined in terms of cut. not(x) :- call(x),!, fail. not(x). 14 14

State the binding time for the following if #define D = 10 printf( %s, Hello World ) Design Time Compile Time Link Time class Base(object): def a_method(self): print "a_method was called" def dangerous(self): print "Replacing methods can cause tricky bugs!" Base.a_method = dangerous Run Time 15 15

Describe a memory allocation policy for short and long lived objects int a = 10; // Short Time on the stack int *a = (int *)malloc(sizeof(int)) // Long Lived on the Heap *a = 10 16 16

What does a language that supports function calls need to implement? A runtime stack. 17 17

What is kept on a runtime stack? Parameters Local Variables of the function Where to return once the function exits Extra Credit: What are 2 assembly instructions on x86 for stack managment? Push and Pop 18 18

How did Fortran support Subroutines? Static Allocation of Memory What is the disadvantage of Static Allocation? Waste of Memory, Limited Recursion depth 19 19

What are the 4 steps of a Call Sequence Setup, before call to subroutine. Prologue, before subroutine body executes. Epilogue, after subroutine body completes (the return). Cleanup, right after subroutine call. 20 20

What are the 3 ways to pass parameters Pass By Value: C/C++ Pass By Reference: C/C++, Java Pass By Name: Haskell 21 21

List all common parameter types and their purpose. positional: normal parameters optional/default: parameters that are mostly the same variable parameters: no predetermined number of actual parameters keyword parameters: can appear in any order 22 22

How can you avoid exponential recursion Use Tail Recursion Pass values to the next stage instead of a evaluating a function to retrieve the value 23 23

How can you optimize evaluation of a boolean expression? Use short-circuit HashMap dict = null; // possibly initialized by other code if (dict!= null && dict.contains("key")) // do something; 24 24

What is the referencing environment? The set of all active bindings; all valid names 25 25

What do you need to implement a nested subroutine? Closest nested scope: a binding is active in the scope in which it is declared and in each nested scope, unless it is shadowed by another binding Need Symbol Table support. Push a new frame onto the stack 26 26

What is an anonymous function? Simply a function that is not bound to a name. Anonymous functions are not necessarily nested, and not necessarily a function parameter. Lambda Expressions: print 'by last', sorted(strings, key=lambda x: x[-1]) (lambda x: x * x)(2) 27 27

In a nested subroutine, what is a free variable? Any variable that is neither a formal parameter (passed to the function) nor a local declaration. 28 28

What is a closure? A nested subroutine in which the free variables are bound to entities (objects) residing in the lexical scope in which the nested subroutine was defined. 29 29

Closure Example: A Hidden Stack Python: Output: def make_stack(): mystack = [] def _push(x): mystack.append(x) def _pop(): val = mystack[-1] del mystack[-1] return val return (_push, _pop) b: 3 2 1 d: 7 8 9 (a, b) = make_stack() (c, d) = make_stack() a(1); a(2); a(3) c(9); c(8); c(7) print 'b:', b(), b(), b() print 'd:', d(), d(), d() 30 30

What s the difference between callby-name and inlining? Call-by-name is a function call semantics (that could be implemented in different ways). It defines how parameters are used. Inlining is a compiler optimization (that may not change the calling semantics). It applies to how a function is called. Inlining can apply to any function call semantic. 31 31

What is the key benefit of a statically, weakly typed language? Execution speed: no runtime checks are required. 32 32

Which data type fundamentally requires runtime checks in a strongly typed language? Disjoint union types; tag checks must occur at runtime. 33 33

Disjoint Union One value, chosen from multiple (disjoint domains). Mathematical view. Simply a union of all possible types (= sets of values). Each value is tagged to tell to which domain it belongs. Tag can be used for checks at runtime. ({1} S) ({2} T )={(t, x) (t =1 x S) (t =2 y T )} Example: A pixel color can be defined using RGB (red, green, blue color channels) or HSB (hue, saturation, brightness). Both are simply three-tuples, but values must be distinguished at runtime in order to be rendered correctly. 34 34

Disjoint Union in Haskell enumeration of named tuples Algebraic data type. Generalizes enumeration types and composite types. -- Implicit fields: only types are given, no explicit names -- These can be accessed using pattern matching -- (de-structuring bind). data Coordinate = Coord2D Int Int Coord3D Int Int Int -- Enumeration type. data ColorName = White Black Green Red Blue CarolinaBlue -- Explicit field names. data Color = RGB { red :: Int, green :: Int, blue :: Int} Named ColorName HSB { hue :: Double, sat :: Double, bright :: Double} -- Composite type of composite types. -- Again, implicit fields. data Pixel = Pixel Coordinate Color 35 35

When is a recursive function call tailrecursive? When it is the last expression to be evaluated before the return from the function 36 36

When is a recursive function tail-recursive? When every possible control flow path contains either: 1) exactly one recursive call that is tail-recursive, or 2) no recursive call a all. In other words, a single non-tail-recursive call is sufficient to render a function non-tail-recursive. 37 37

Is this function tail-recursive? Why? def recsum(x): if x==1: return x else: return x+recsum(x- 1) No, the function is not tail-recursive, since the recsum needs to be evaluated before ʻ+ʼ can occur 38 38

Fix the previous recursive function def tailrecsum(x,running_total=0): if x==0: return running_total else: return tailrecsum(x- 1,running_total+x) 39 39

Explain early and late binding in the context of object-oriented languages. With early binding, the method being invoked is determined at compile time based on the type of the reference. With late binding, the method being invoked is determined at run time based on the type of the value (i.e., the object). 40 40

Name two advantages of delegation. 1) Avoids the fragile base class problem. 2) Facilitates the use of fat interfaces, i.e., interfaces that require many methods to be implemented. Does Java support delegation? No!! 41 41

Delegation Example interface Bar { void bar(); } class DefaultBar implements Bar { void bar() {... }; } class MyClass implements Bar { private DefaultBar barimpl = new DefaultBar(); } void bar() { barimpl.bar(); } C# provides explicit delegate syntax 42 42

Whatʼs monkey patching? Modification of classes at runtime (adding / removing / replacing methods and attributes). 43 43

Give an example of a language that supports runtime modification of its objects and classes? Python with a caveat?? Library does not have a C backend 44 44

The class concept is fundamental to all object-oriented languages. True or false? (Why?) No, prototype-based languages do not require classes 45 45

Give three uses of a RTS Garbage Collection Error Checking Just-In-Time Compilation 46 46

Describe how a Mark-Sweep GC works? 47 47

What is wrong with this graph when Ref Counting is used? stooges 2 larry 1 moe Stack Heap 1 curly stooges 1 larry 1 moe Stack Memory Heap leak when stooges 1 curly is freed 48 48

How would you fix the previous graph? Use tags with ref count to make sure stack and heap references are separated. 49 49

How much memory is available in a Copy Based GC? Half the memory, as you maintain a free and used regions 50 50

What is Finalizer and When do you use it? Release all non-memory resources e.g. File Handles, Thread resources 51 51

What is the possible catch-22 in GC? GC runs when memory is low, and GC needs memory to run. Concurrent GCʼs solve this problem 52 52

When does JIT code incur penalty and how many times? One-time penalty, initially when the byte code is compiled for heavily used objects For rarely used code segments, penalty is proportional to the number of accesses. 53 53

How is Binary Translation different from JIT? BT works on machine code to machine code transformation e.g. ESX server uses BT to implement virtualization JIT works at the level of byte code. e.g. Jave uses JIT to speedup runtime of applications 54 54

When can JIT be more aggressive? Long lived applications, allows the JIT to learn from its mistake and better amortize the cost of a mistake. e.g. Server apps of Java. 55 55

What is the difference between MultiProgramming and MultiThreaded programming Multiprogramming gives you the illusion of concurrency by interleaving processes on a single CPU Multi-threaded programs on multiple processors have the ability to concurrently run at the same time 56 56

Speedup: If a task takes time ʻtʼ on one processor, on ʻnʼ processors should the time be t/n? No, Amdahlʼs law: The speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program. 57 57

How many students did actually submit review questions? 58 58