Instituto Superior Técnico. First Exam 7/6/2013. Number:

Similar documents
First Exam/Second Test 19/6/2010

Multi-Methods in Racket

Querying Microsoft SQL Server 2014 (20461)

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Run-time Environments

Run-time Environments

CS 415 Midterm Exam Spring 2002

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Programming Languages Third Edition. Chapter 7 Basic Semantics

Concepts Introduced in Chapter 7

Basics of Using Lisp! Gunnar Gotshalks! BLU-1

Generic Functions in Java

Picasa web download photos. Picasa web download photos.zip

Run-time Environments. Lecture 13. Prof. Alex Aiken Original Slides (Modified by Prof. Vijay Ganesh) Lecture 13

Names, Scope, and Bindings

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

Introdução e boas práticas em UX Design (Portuguese Edition)

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Names, Scope, and Bindings

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

Metamodeling and Metaprogramming Seminar

CORBA Based Architecture for Large Scale Workflow. Master thesis defended in August 21 st, Institute of Computing UNICAMP Campinas - SP

Super bluetooth phone hacker. Super bluetooth phone hacker.zip

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

NOTE: Answer ANY FOUR of the following 6 sections:

MATLIP: MATLAB-Like Language for Image Processing

1. Consider the following program in a PCAT-like language.

MIDTERM EXAMINATION - CS130 - Spring 2003

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

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

CSC 533: Organization of Programming Languages. Spring 2005

CSCI Compiler Design

CS558 Programming Languages. Winter 2013 Lecture 3

CS 314 Principles of Programming Languages

New Programming Paradigms

Programming Languages

CA Compiler Construction

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

The role of semantic analysis in a compiler

Page 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics

LECTURE 17. Expressions and Assignment

Componentes de. Resumido e Adaptado dos apontamentos do Prof. José Tavares (Ambientes de Desenvolvimento Avaçados)

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Java Reflection

The PCAT Programming Language Reference Manual

Repensando Templates com Cryml. Dalton Pinto

Principles of Programming Languages

Names, Scope, and Bindings

Linguistic Reflection Via Mirrors

Lecture 16: Static Semantics Overview 1

Lexical Considerations

CSE3322 Programming Languages and Implementation

Contents in Detail. Who This Book Is For... xx Using Ruby to Test Itself... xx Which Implementation of Ruby?... xxi Overview...

Sistemas Distribuídos com Redes de Sensores. Noemi Rodriguez

AspectC++ A Language Overview

1 Lexical Considerations

Microsoft net framework 2.0 windows 7 32 bit. Microsoft net framework 2.0 windows 7 32 bit.zip

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

CS558 Programming Languages

TRI para escalas politômicas. Dr. Ricardo Primi Programa de Mestrado e Doutorado em Avaliação Psicológica Universidade São Francisco


Partition magic 10 portable. Partition magic 10 portable.zip

Programming Language Concepts: Lecture 10

Python Implementation Strategies. Jeremy Hylton Python / Google

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

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

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

Grade Weights. Language Design and Overview of COOL. CS143 Lecture 2. Programming Language Economics 101. Lecture Outline

CS153: Compilers Lecture 15: Local Optimization

Names, Scopes, and Bindings. CSE 307 Principles of Programming Languages Stony Brook University

Run Time Environment. Procedure Abstraction. The Procedure as a Control Abstraction. The Procedure as a Control Abstraction

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Names, Scope, and Bindings

CSE 307: Principles of Programming Languages

The compilation process is driven by the syntactic structure of the program as discovered by the parser

10. Functions (Part 2)

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS

CSCE 314 Programming Languages

Deploying and Managing Windows 10 Using Enterprise Services ( )

Macros. Pat Hanrahan. CS448h Fall 2015

NADABAS and its Environment

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

Hotmail.com login login

Lambda Calculus LC-1

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

Equivalent Notations. Higher-Order Functions. (define (f x y) ( body )) = (define f (lambda (x y) ) ) Anonymous Functions.

Parsing II Top-down parsing. Comp 412

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

Improving Variability of Applications using Adaptive Object-Models

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Common Lisp Object System Specification. 1. Programmer Interface Concepts

6. Names, Scopes, and Bindings

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Run Time Environment. Activation Records Procedure Linkage Name Translation and Variable Access

IR Generation. May 13, Monday, May 13, 13

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY Fall Quiz I

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

Transcription:

Instituto Superior Técnico Programação Avançada First Exam 7/6/2013 Name: Number: Write your number on every page. Your answers should not be longer than the available space. You can use the other side of the page for drafts. The exam has 6 pages and the duration is 2.0 hours. The grade for each question is written in parenthesis. Good luck. 1. (2.0) Explain the concepts of introspection and intercession and provide one example for each of them. A Introspecção é a capacidade de um sistema de observar a sua própria estrutura e comportamento. Por exemplo, saber Quantos parâmetros tem a função foo? é introspecção. A Intercessão é a capacidade de um sistema de modificar a sua própria estrutura e comportamento. Por exemplo, Mudar a classe desta instância para Bar é intercessão. 2. (1.0) In order to allow introspection, the Java language had to reify the concept of class and had to provide three different ways for obtaining a class. Write fragments of Java programs that show each of these three different ways of obtaining a class. "I am a string".getclass() String.class Class.forName("java.lang.String")

Number: 2 3. (1.0) In an object oriented language, some classes might represent objects with a lot of functionality but very little data, while other classes might represent objects containing a lot of data but little functionality. These different classes can be compared by computing, for a given class, the m f+m functionality ratio, where m is the total number of public methods and f is the total number of public fields. A ratio of 1 means that the instances of the class do not contain public fields, while a ratio of 0 means that the instances do not contain public methods. Write, in Java, a class named Metrics containing a static method named functionality. This method accepts a Class as an argument and returns a double expressing the functionality ratio of the class. import java.lang.reflect.*; class Metrics { public static double functionality(class c) { int m = c.getmethods().length; return ((double) m)/(m + c.getfields().length); 4. (1.0) Consider the following fragment of Java code: Class cls = Class.forName("FooBar"); Method meth = cls.getmethod("baz"); meth.invoke(cls.newinstance()); Rewrite the fragment so that you obtain the same result but without using any reflection mechanisms. new FooBar().baz();

Number: 3 5. (2.0) There are several proposals for the inclusion of multiple dispatch in Java. Explain this concept and write about the advantages and disadvantages of its implementation in Java. In particular compare the concept with the already existent concept of overloading. Multiple dispatch vs single dispatch plus overloading. Run time types vs compile time types. Cascaded ifs plus instanceof vs double dispatch pattern vs reflection. 6. (2.0) Some programming languages allow an instance of a class to become a member of a different class. Explain the advantages and disadvantages of that possibility. As vantagens incluem: Aumento de poder expressivo: permite escrever programas mais simples do que quando isso não é possível. Possibilidade de criar instâncias quando ainda não é bem conhecida a classe a que devem pertencer e poder especificar essa classe mais tarde. Permitir actualizar as instâncias já existentes sem ter de fazer redeploy da aplicação As desvantagens incluem: Implementação mais complexa da linguagem. Ineficiências no acesso às instâncias ou na mudança de classe. Dificuldades de optimização. Funcionamento do programa difícil de entender. Depuração mais difícil.

Number: 4 7. (1.0) CLOS provides the protocol update-instance-for-redefined-class. Why does it exist? What can we do with it? When is this protocol executed? The protocol exists because CLOS allows classes to be redefined at run time and instances need to know about that so that they can be updated. The protocol allows the programmer to write code that migrates the values of the previous slots of an instance to the slots prescribed by the redefined class. The protocol is not executed when the class is redefined. Instead, it is executed when an instance of a redefined class is accessed. 8. (2.0) In general, aspect-oriented programming allows not only the dynamic cross-cutting but also the static cross-cutting. Describe and explain the capabilities of each of these concepts. O cross-cutting dinâmico implica a modificação do comportamento de um programa, permitindo a inserção de comportamento adicional em pontos bem definidos da execução do programa. O cross-cutting estático implica a modificação da estrutura estática do programa, permitindo modificações na hierarquia de class, a adição de methods, a implementação de novas interfaces, etc. 9. (1.0) Describe, in your own words, the effect of the following aspect of AspectJ: aspect FooAspect { static final int LIMIT = 100; before(foo foo, int newbar): set(int Foo.bar) && target(foo) && args(newbar) &&! within(fooaspect) { if (newbar > LIMIT) { foo.bar = LIMIT;

Number: 5 10. (1.0) The Common Lisp language provides the forms function (# ) and funcall, while the Scheme language does not provide them. Why? Explain. Scheme has a single namespace for functions and variables, while Common Lisp has different namespaces for those. In Scheme, a name only means one thing at any given instant, but in Common Lisp it can mean several things and the language disambiguates by considering that a name in the first position of a non-atomic expression refers to a function while in the other positions it refers to a variable. The forms function and funcall are used to change this meaning. 11. (2.0) Some languages, such as Pascal, allow functions to be defined inside other functions, but do not allow functions to be returned as values or to be stored in variables. Some other languages, such as C, allow functions to be returned as values or to be stored in variables, but do not allow functions to be defined inside other functions. What problem explains those two different approaches to language design? If you want to have a language that has the same capabilities of both Pascal and C, what should you do? Explain all implications. In order to be lexically scoped, the free variables of a function must be bound to the values that were available when the function was created. Given that it is impossible to predict the moment when the function is called, those values must be available until the function can no longer be called. Pascal saves those values on the stack and this means that functions cannot outlive the containing function, while C forces all free variables to have global scope, thus preventing internal function definitions. To solve the problem, each function must contain a reference to the lexical environment that was available when the function was created, and this environment must have indefinite extent, which usually requires garbage collection. 12. (1.0) Consider the yield operator as provided in Python. What does it do? What is it used for? The operator is used to allow a function to resume its computation from the point where it previously returned. Whenever a yield is reached, the function returns a value but also saves its execution state so that the next time it is invoked, it resumes from where it was. This is used to implement generators.

Number: 6 13. (1.0) Using the ambiguous operators amb and fail, define a function named integer-between that accepts two integers a and b as arguments and non-deterministically returns an integer i such that a i b. (define (integer-between a b) (if (> a b) (fail) (amb a (integer-between (+ a 1) b)))) 14. (1.0) What kind of problem is a good match for non-deterministic computation? Explain. Problems where there are alternative ways for continuing a computation and where backtracking is required for findind the correct way that leads to a solution. 15. (1.0) Julia is a recently proposed programming language with metaprogramming capabilities. As an example, the following fragment defines three-argument versions of the two-argument predefined operators foo and bar: for op = (:foo, :bar) eval(:($op(a,b,c) = $op($op(a,b),c))) end What must be the purpose of the symbols : and $? Explain. Given that the example uses the eval function, its argument must be a fragment of code. In this case, the symbol : must have the same meaning as the backquote in Lisp, and $ must have the same meaning as the comma, i.e., the : does not evaluate the expression except in the subexpressions preceeded by $. These symbols are being used for creating templates that simplify meta-programming.