FACIT TILL TENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13: 15

Relevanta dokument
TENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13: 15

TENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13:15

OMTENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13: 15

DVG C01 TENTAMEN I PROGRAMSPRÅK PROGRAMMING LANGUAGES EXAMINATION :15-13: 15

FACIT TILL OMTENTAMEN I PROGRAMSPRÅK DVG C01

FACIT TILL OMTENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13: 15

FACIT TILL/TO DVG C01 OMTENTAMEN I PROGRAMSPRÅK PROGRAMMING LANGUAGES RESIT EXAMINATION :15-13: 15

FACIT TILL OMTENTAMEN I PROGRAMSPRÅK -- DVG C kl. 08:15-13: 15

FACIT TILL OMTENTAMEN I PROGRAMSPRÅK DVG C kl. 08:15-13:15

Recitation 4. 2-D arrays. Exceptions

Imperative Programming

Tentamen i. TDDA 69 Data och programstrukturer

Vad kännetecknar en god klass. Vad kännetecknar en god klass. F12 Nested & Inner Classes

Isometries of the plane

Styrteknik: Binära tal, talsystem och koder D3:1

Schenker Privpak AB Telefon VAT Nr. SE Schenker ABs ansvarsbestämmelser, identiska med Box 905 Faxnr Säte: Borås

Discovering!!!!! Swedish ÅÄÖ. EPISODE 6 Norrlänningar and numbers Misi.se

Grammatik. BNF-grammatik

Föreläsning 3. Stack

Klassdeklaration. Metoddeklaration. Parameteröverföring

Att skriva till och läsa från terminalfönstret

Tentamen Grundläggande programmering

Föreläsning 3. Stack

Classes och Interfaces, Objects och References Objekt-orienterad programmering och design (DIT952) Niklas Broberg, 2016

Tentamen Programmering fortsättningskurs DIT950

GU / Chalmers Campus Lindholmen Tentamen Programutveckling LEU 482 / TIG167

Module 6: Integrals and applications

Classes och Interfaces, Objects och References, Initialization

TDA550 Objektorienterad programvaruutveckling IT, forts. kurs Övning vecka 2

Tentamen i Matematik 2: M0030M.

Kompilering och exekvering. Föreläsning 1 Objektorienterad programmering DD1332. En kompilerbar och körbar java-kod. Kompilering och exekvering

Support Manual HoistLocatel Electronic Locks

Uttagning för D21E och H21E

TDDC30. Kursledning Kursledare: Jonas Lindgren. Labassistent: Jonas Lindgren Labassistent: Niklas Holma Labassistent: Erik Nilsson

Beijer Electronics AB 2000, MA00336A,

Lösningsförslag till omtentamen för TDA540 Objektorienterad Programmering

FACIT TILL TENTAMEN I PROGRAMSPRÅK DVG C kl. 08:15-13:15

denna del en poäng. 1. (Dugga 1.1) och v = (a) Beräkna u (2u 2u v) om u = . (1p) och som är parallell

LUNDS TEKNISKA HÖGSKOLA Institutionen för Elektro- och Informationsteknik

kind spelling Scanning

Authentication Context QC Statement. Stefan Santesson, 3xA Security AB

Viktig information för transmittrar med option /A1 Gold-Plated Diaphragm

1. Varje bevissteg ska motiveras formellt (informella bevis ger 0 poang)

Calculate check digits according to the modulus-11 method

LULEÅ TEKNISKA UNIVERSITET

12.6 Heat equation, Wave equation

Tentamen MMG610 Diskret Matematik, GU

TDDC74 Programmering: Abstraktion och modellering Dugga 2, , kl 14-16

Tentamen FYTA11 Javaprogrammering

/* * * Lösningsförslag tentamen DIT950 * Datum * */ /* * -1 - */ För samtliga gäller,se föreläsningsanteckningar.

OMTENTAMEN I DATASTRUKTURER OCH ALGORITMER DVG B kl. 08:15 13:15

Alfabeten, strängar och språk. String

Schenker Privpak AB Telefon VAT Nr. SE Schenker ABs ansvarsbestämmelser, identiska med Box 905 Faxnr Säte: Borås

1. Compute the following matrix: (2 p) 2. Compute the determinant of the following matrix: (2 p)

Tentamen Programmeringsteknik II Skrivtid: Hjälpmedel: Java-bok (vilken som helst) Skriv läsligt! Använd inte rödpenna!

List.java. List.java. Printed by Tom Smedsaas

12. Relationer och funktioner

This exam consists of four problems. The maximum sum of points is 20. The marks 3, 4 and 5 require a minimum

Isolda Purchase - EDI

FÖRBERED UNDERLAG FÖR BEDÖMNING SÅ HÄR

VHDL Basics. Component model Code model Entity Architecture Identifiers and objects Operations for relations. Bengt Oelmann -- copyright

x 2 2(x + 2), f(x) = by utilizing the guidance given by asymptotes and stationary points. γ : 8xy x 2 y 3 = 12 x + 3

Objektorienterad Programkonstruktion. Föreläsning 2 2 nov 2016

Examination i. PROGRAMMERINGSTEKNIK F1/TM1 TIN212 (Dugga) Dag: Onsdag Datum: Tid: (OBS 3 tim) Rum: V

Föreläsning 4 IS1300 Inbyggda system

Det är principer och idéer som är viktiga. Skriv så att du övertygar rättaren att du har förstått dessa även om detaljer kan vara felaktiga.

F4. programmeringsteknik och Matlab

Inlämningsuppgift MiniPlotter

Materialplanering och styrning på grundnivå. 7,5 högskolepoäng

Detta dokument är ett exempel, cirka andra hälften av en tentamen för TDA545 Objektorienterad programvaruutveckling

Mutability och State. Objekt-orienterad programmering och design (DIT953) Niklas Broberg / Johannes Åman Pohjola, 2018

Tentamen Programmeringsteknik II Inledning. Anmälningskod:

Programmering I Tobias Wrigstad fredag, 2009 augusti 28

Michael Q. Jones & Matt B. Pedersen University of Nevada Las Vegas

Preschool Kindergarten

Sätt att skriva ut binärträd

Obligatorisk uppgift 5

Styrteknik : Funktioner och funktionsblock

Objektsamlingar i Java

E02 "The Review" Föreläsning 2, HT2013 Grunderna, repetition. Johan Leitet. Kurs: 1dv403 Webbteknik I

Outline. Objektorienterad Programmering (TDDC77) En frukt har ett namn. Man kan lägga en frukt i en korg... Hashing. Undantag. Ahmed Rezine.

Föreläsning 10 Datalogi 1 DA2001. Utskrift på skärmen. Syntax. print( Hej ) Hur är det? Hej. print( Hej,end= ) print( Hur är det? ) HejHur är det?

Lösningsförslag. Programmeringsmetodik, KV: Java och OOP. 17 januari 2004

TDDC74 Programmering: Abstraktion och modellering Dugga 2, , kl 17-19

Webbregistrering pa kurs och termin

Övning 1 - Abstrakta datatyper

OMTENTAMEN I DATASTRUKTURER OCH ALGORITMER DVG B kl. 14:15 19:15

Programmering med Java. Grunderna. Programspråket Java. Programmering med Java. Källkodsexempel. Java API-exempel In- och utmatning.

DAT043 Objektorienterad Programmering

tentaplugg.nu av studenter för studenter

TENTAMEN PROGRAMMERINGSMETODIK MOMENT 2 - JAVA, 4P

Algoritmer och Komplexitet ht 08. Övning 6. NP-problem

TDDC74 FÖRELÄSNING 9 ANDERS MÄRAK LEFFLER IDA/HCS

Repetition C-programmering

Chapter 4: Writing Classes/ Att skriva egna klasser.

Abstrakt datatyp. -Algoritmer och Datastrukturer- För utveckling av verksamhet, produkter och livskvalitet.

TDDC30. Objektorienterad programmering i Java, datastrukturer och algoritmer. Föreläsning 1 Jonas Lindgren, Institutionen för Datavetenskap, LiU

c = s[2]; /* move chars around */ p = &s[2]; *p = *(p-1); --p; *p = *(p-1); s[0] = c; printf("%s\n",s); /* print the string */ English version

Grafer, traversering. Koffman & Wolfgang kapitel 10, avsnitt 4

TENTAMEN PROGRAMMERING I JAVA, 5P SOMMARUNIVERSITETET

Transkript:

FACIT TILL TENTAMEN I PROGRAMSPRÅK -- DVG C01 130607 kl. 08:15-13: 15 Ansvarig Lärare: Donald F. Ross Hjälpmedel: Bilaga A: BNF-definition Betygsgräns: Kurs: Max 60p, Med beröm godkänd 50p, Icke utan beröm godkänd 40p, Godkänd 30p (varav minimum 20p från tentan, 10p från labbarna) Tenta: Max 40p, Med beröm godkänd 34p, Icke utan beröm godkänd 27p, Godkänd 20p Labbarna: Max 20p, Med beröm godkänd 18p, Icke utan beröm godkänd 14p, Godkänd 10p SKRIV TYDLIGT LÄS UPPGIFTERNA NOGGRANT 1. Ange kortfattade svar på följande uppgifter: (a) Ge en definition av (i) aktuell parameter samt (ii) formell parameter - an actual parameter is an expression (this includes id!) - a formar parameter is an identifier (b) Förklara skillnaden mellan A och A i Lisp. - A is a symbol which can be evaluated and its value used - A (quote A) is an unevaluated form A is treated as a literal symbol (c) Förklara skillnaden mellan begreppen syntax och semantiken. - syntax describes the structure of a language often by means of a formal grammar - semantics describes the meaning of ther language constructs often using natural language (e.g. English, Swedish) and less often a formal mathematical notation e.g. Z, denotational semantics (d) Vilken roll spelar typ i programspråk? - a type defines a set of values; variables (data objects) are instances of a type (similarly an object in the OO world is an instance of a class); operators may be defined on types and type expressions written as operator: type 1 x type 2 x x type n type k which then may be used in type checking of expressions in the language. A Type may also be used as self-documentation in a program; types are also used to provide signatures for functions (methods) DFR/EJN/ND 130607 PS tentamen - facit Sidan 1 av 20

(e) Vad är skillnaden mellan lifetime och scope? - lifetime is the length of time an object exists in memory and is accessible - scope determines if a named object is accessible (visible) in a given environment firstly the local environment is checked and then the nion-local environment according to the sematic rules given in the language semantics (f) Vad är ett 3G -programmeringsspråk? - 3G stands for Third Generation and is applied to languages (also known as highlevel languages) to distinguish these languages from machine code (1G) and assembler language (2G). 3Gs started with Fortran IV and Algol 60. The advantage of 3G languages was that the programs were more readable by human beings. 3Gs went through an evolution in the 1970s with structured programming and gave rise to the OO languages in the 1980s (Smalltalk, C++) (g) Vad är flödeskontroll ( flow-of-control )? - FOC provides statements to determine the order in which the expressions in a programming language are executed - the default is sequential - decision constructs (if-then(-else); case/switch) allow different paths to be executed in the code sequence - repetition (while; for; do-while; repeat-until) allows sections of code to be executed repeatedly. - branch (jump) instructions (goto; break; continue) allow execution to jump to a different part of the code sequence - essentially only 2 constructs are really required: if X goto/goto i.e. conditional and unconditional got o (h) Förklara definitionen G = (S, P, NT, T). - G is the grammar defined by - S the start symbol (a non-terminal) - P a set (sequence) of transformation (substitution) rules stating how each non- Terminal symbol may be substituted - NT is the set of non-terminal symbols which appear on the RHS (right hand side) of a production P -T is the set of Terminal symbols which cannot e further substituted. The Ts as the ssymbols which appear in the program text DFR/EJN/ND 130607 PS tentamen - facit Sidan 2 av 20

(i) Vad är en RDPP ( Recursive Descent Predictive Parser )? - an RDPP is a parser (usually written by hand) which uses recursion (from the recursive definition in the grammar G); the Descent part comes from the sequence of procedure calls which forms a (parse) tree (hence descending into the tree from the root which is the start symbol S; the predictive part comes from the grammar, often written as an LL(1) grammar where the current input symbol (token) from the input stream is used to determine (predict) the next grammar rule to be applied. E.g. for a statement in a language, the choices might be assignment (begins with an ID), if statement (begins with the keyword IF), while statement (begins with the keyword WHILE), case statement (keyword CASE) etc. As long as each of these tokens is unique for each kind of statement, the token can be used to determine the next procedure to call. Given the grammar, there are rules of thumb which state that each NT in the grammar is implemented as a procedure and each T in the input streaqmr is checked against the expected T according to the grammar (procedure match). (j) Vad är skillnaden mellan den lokala omgivningen ( local environment ) och den ickelokala omgivningen ( non-local environment )? - at each point in the execution, there exists a name space which is defined by the semantics of the language (usually either static or dynamic) - this namespace can be defined by the local environment for e.g. the current function being executed, the local objects these will be defined in the symbol table for the function and allocated space in the stack frame for the current execution of the function and a non-local environment whic refers to visible objects not defined in the function. - the non-local objects may be accessed if the scope rules allow often expressed as non-local objects being visible in the function - these concepts are often illustrated by box drawings Program xyz Function f1 Function f2 Function f3 Data: a, b, c Data: a d e Data c d f Data a, b In function f1 a, d, e are local b, c from program xyz are nonlocal but visible In function f2 c, d, f are local a and b from program xyz are non-local but visible In function f3 a, b are local c, d, f from function f2 are nonlocal but visible Totalt 10p DFR/EJN/ND 130607 PS tentamen - facit Sidan 3 av 20

2. BNF-definitioner Titta noggrant på grammatiken i bilaga A. Utöka denna BNF-definition för att hantera funktioner. Ange alla antagande. 5p [function def list] ::= e [function def] [function def list] [function def] [function def] ::= [function header] [var part] [stat part] [function header] ::= function id ( [parameter list] ) : [ type] ; [parameter list] [param dec list] [param dec] ::= e [param dec list] ::= [param dec] [param dec list], [param dec] ::= { var [id list] : [type] Now add the [function def list] into the grammar [program] ::= [prog header] [var part] [function def list] [stat part] NB it is also an idea to update [operand] [operand] ::= id number [function call] [function call] ::= id ( actual param list ) [actual param list] ::= e [expression list] [expression list] ::= [expr] [expression list], [expr] By analogy with a program The parameter list may be empty (design decision) This is also similar to a [var dec list] except that it is separated by a comma and not terminated by a semicolon The var part is optional here I use EBNF [param dec] ::= var [id list] : [type] [id list] : [type] Would be the alternative DONE! DFR/EJN/ND 130607 PS tentamen - facit Sidan 4 av 20

3. Diskussion - Rekursion Vilken roll spelar rekursion i både programspråk samt programparadigmer? Använd gärna konkreta exempel i ditt svar. Svar ingående. Programming Languages 5p Recursion commonly occurs in 2 forms in computing o Recursive definitions e.g. in grammars such as G = (S, P, NT, T) o Recursive calls One common ADT which may be recursively defined is the list o L ::= H T ; H ::= element; T ::= L o This definition is reflected in the operations that the language provides to manipulate lists In implementing RDPPs, recursive calls are often used which reflects the recursion in the grammar definition Recursion often appears as tail recursion or recursion using auxiliary functions (A calls B and B calls A indirect recursion) e.g. in a grammar implementation id_list() { match(id); if (lookahead == ',') { match(','); id_list(); Programming Paradigms In the logic and function programming paradigms, recursion is the only method of implementing repetition (Lisp includes other structures such as loop but these are nonfunctional Recursion can also be thought of as a thought model i.e. a way of approaching ADTs (commonly lists, binary trees) and programming operations This in turn leads to programming patterns or clichés o Add in a list (implemented in C) static listref b_add(int v, listref L) { return is_empty(l)? create_e(v) : v < get_value(head(l))? cons(create_e(v), L) : cons(head(l), b_add(v, tail(l))); Marks for good examples and good discussion. DFR/EJN/ND 130607 PS tentamen - facit Sidan 5 av 20

4. Exekveringstidsystem ( Run-time System ) Givet programmet nedan, förklara ingående förhållandena mellan programmets text (källkoden), symboltabellen och hur den exekveringsstack hanteras under programexekvering. Ange alla antagande. 5p program xyz (input, output); var a, b, c: integer; p, q: boolean; integer function x(fp1: integer, fp2: integer); begin var i: integer; integer function y(fp1: integer, fp2: integer); var i: integer; begin i := fp1 * fp2; return i; end y. begin i := y(fp1, fp2) + y(fp1, fp2); return i; end x. a := 2; b := 3; c := x(a, b); print c; end xyz. DFR/EJN/ND 130607 PS tentamen - facit Sidan 6 av 20

The symbol table for the above program may be implemented as a tree xyz program a variable integer 0 b variable integer 4 c variale integer 8 p variable boolean 12 q variable boolean 16 x function integer x function integer fp1 f-parameter integer 0 fp2 f-param integer 4 i variable integer 8 y function integer y function integer fp1 f-param integer 0 fp2 f-param integer 4 i variable integer 8 This gives the storage information (as stack frame offsets). The call sequences are:- 1. xyz x y (first call of y) 2. xyz x y (second call of y) The stack frames will therefore be STACK FRAME Formal parameters Local data bojects Static pointer Dynamic pointer Return value Return address y y xyz x xyz x Xyz x xyz x xyz xyz Explain the roles of thye static/dynamic pointers, parameter passing mechanisms. Marks for good examples and explanations. DFR/EJN/ND 130607 PS tentamen - facit Sidan 7 av 20

Uppgiften fattades från den ursprungliga tentan. Upptäckt kl 08:05 130607. Levererades separat till tentalokalen 130607 08:30 5. Parseträd expr -> term R1 R1 -> e '+' term R1 term -> factor R2 R2 -> e '*' factor R2 factor -> '(' expr ')' DIGIT (e = empty) Titta noggrant på grammatiken ovan. Rita parseträdet för uttrycket (2+2)*2. 5p DFR/EJN/ND 130607 PS tentamen - facit Sidan 8 av 20

expr factor term R2 R1 e ( expr ) * factor R2 digit e term R1 2 factor R2 + term R1 digit e factor R2 e 2 digit e 2 ( 2 + 2 ) * 2 DFR/EJN/ND 130607 PS tentamen - facit Sidan 9 av 20

6. Prolog a) Predikat Skriv predikatet langd(+lista,-antal), som tar Lista som inparameter och returnerar antalet element i Lista genom parametern Antal Exempel:?- langd([a, b, c], X). X = 3 (1 p) b) Laborationen I laboration 2 skulle du skriva en parser för ett enkelt Pascalprogram. Parsningsprogrammet kunde delas upp i tre delar: inläsning från fil, lexikalanalys och syntaxanalys. Lexikalanalysdelen fick en lista med fyra typer av lexem (= nyckelord, specialtecken, variabelnamn och heltal) från inläsningsdelen och den listan omvandlades ett lexem i taget till en lista av tokens för vidare behandling i syntaxanalysdelen. a) Skriv predikatet lexer som med hjälp av predikatet match gör om ett lexem i taget till motsvarande token. (1 p) b) Beskriv utförligt, gärna med hjälp av kod, hur match gör omvandlingen till tokens. Beskrivningen skall innehålla minst tre olika typer av lexem. (3 p) Totalt 5p DFR/EJN/ND 130607 PS tentamen - facit Sidan 10 av 20

7. Objektorientering 5 poäng: Följande UML-diagram visar en del av ett system för ritning av grafiska figurer. <<abstract>> GraphicItem Drawing +add(graphicitem) +at(index: int): GraphicItem +drawon(agraphicscontext) +draw() -items * +GraphicItem(location: Point) <<abstract>>+drawon(agraphics) <<abstract>>+extent(): Dimension <<abstract>>+rotate(degrees: int) +location(): Point +setlocation(location: Point) +moveby(distance: Dimension) +moveby(deltax: int, deltay: int) +clone(): GraphicItem Point -location +x: int 1 +y: int Circle -radius:double +Circle(center: Point, radius: int) +radius(): int +extent(): Dimension +drawon(agraphics) +rotate(degrees: int) Line +Line(origin: Point, end: Point) +end(): Point +extent(): Dimension +drawon(agraphics) +rotate(degrees: int) Dimension -extent +width: int 1 +height: int Som ett komplement till klassdiagrammet ges även några delar av koden som är relevanta för uppgiften, för alla klasser bortsett från Point (med x och y) och Dimension (med width och height) med uppenbar innebörd. Koden innehåller vissa invarianter samt för- och eftervillkor som behövs för att lösa uppgiften. All övrig information finns i klassdiagrammen. Koden ges som en livlina om du inte är säker på tolkningen av diagrammen. Frågorna kommer efter koden. DFR/EJN/ND 130607 PS tentamen - facit Sidan 11 av 20

class Drawing: package drawing; import core.designbycontract; import java.util.*; public class Drawing { private List<GraphicItem> items = new ArrayList<GraphicItem>(); public void add(graphicitem itemnotnull) { DesignByContract.precondition(itemNotNull!= null, "Attempt to add null item"); items.add(itemnotnull); public GraphicItem at(int zerobasedindex) { return items.get(zerobasedindex); public void drawon(graphics graphicscontextnotnull) { for (GraphicItem item : items) { item.drawon(graphicscontextnotnull); public void draw() { drawon(getgraphics()); public Graphics getgraphics() { // return a graphic surface to draw on, for instance the screen or printer surface // set aside for the drawing DFR/EJN/ND 130607 PS tentamen - facit Sidan 12 av 20

class GraphicItem: package drawing; import core.designbycontract; public abstract class GraphicItem implements Cloneable { private Point locationnotnull; public GraphicItem(Point locationnotnull) { DesignByContract.precondition(locationNotNull!= null, "Location is null"); setlocation(locationnotnull); abstract public Dimension extentnotnull(); abstract void drawon(graphics graphicscontextnotnull); abstract public void rotate(int degrees); public Point locationnotnull() { return locationnotnull; public void setlocation(point locationnotnull) { this.locationnotnull = locationnotnull; public void moveby(dimension distance) { setlocation(locationnotnull().plus(distance)); public void moveby(int deltax, int deltay) { moveby(new Dimension(deltaX, deltay)); @Override public GraphicItem clone() throws CloneNotSupportedException { return (GraphicItem)super.clone(); // a shallow copy of myself DFR/EJN/ND 130607 PS tentamen - facit Sidan 13 av 20

class Circle: package drawing; import core.designbycontract; /** * @invariant super.locationnotnull() is my center */ class Circle extends GraphicItem { private int radiusnonnegative; public Circle(Point centernotnull, int radiusnonnegative) { super(centernotnull); // must be first statement DesignByContract.precondition(radiusNonNegative >= 0, "Radius negative"); this.radiusnonnegative = radiusnonnegative; private int radiusnonnegative() { return radiusnonnegative; @Override public Dimension extentnotnull() { return new Dimension(2 * radiusnonnegative(), 2 * radiusnonnegative()); @Override public void drawon(graphics graphicscontextnotnull) { // code to draw me on the surface given by the graphics context @Override public void rotate(int degrees) { DFR/EJN/ND 130607 PS tentamen - facit Sidan 14 av 20

class Line: package drawing; import core.designbycontract; /** * @invariant super.locationnotnull() is my origin, end is the other endpoint */ class Line extends GraphicItem { private Dimension extentnotnull; public Line(Point originnotnull, Point endnotnull) { super(originnotnull); // must be first statement DesignByContract.precondition(endNotNull!= null, "Line endpoint is null"); extentnotnull = endnotnull.minus(originnotnull); public Point endnotnull() { return locationnotnull().plus(extentnotnull()); @Override public Dimension extentnotnull() { return extentnotnull; @Override public void drawon(graphics graphicscontextnotnull) { // code to draw me on the surface given by the graphics context @Override public void rotate(int degrees) { // code to rotate me around my origin A. Var i detta system utnyttjas följande objekt-orienterade mekanismer? Ge om möjligt minst ett precist, konkret exempel för varje mekanism. Det räcker inte att bara säga t.ex. att en mekanism används i klass si och så, utan du ska precisera på vilket sätt den utnyttjas. Om en mekanism utnyttjas på mer än ett ställe ska två exempel ges, om möjligt från två olika klasser. Om en mekanism inte används ska du kort beskriva vad den innebär och ev relatera till vad som gör att den inte tillämpas i exemplet. Fullständiga svar ger 0,5 poäng var, ofullständiga svar ger noll poäng. (2p) a) polymorfism b) arv c) delegering d) omdefiniering (overriding) B. Metoden main i Drawing ser ut som följer. Rita upp resultatet vid referens (1) resp (2). Rikta x-axeln åt höger. Du kan välja att rikta y-axeln uppåt och rotera moturs eller rikta y-axeln neråt och rotera medurs. Varje korrekt ritning ger 0,5 poäng. (1p) DFR/EJN/ND 130607 PS tentamen - facit Sidan 15 av 20

public static void main(string[] args) { Drawing thedrawing = new Drawing(40, 40); Line aline = new Line(new Point(10, 20), new Point(30, 20)); // origin, end Circle acircle = new Circle(new Point(20, 20), 10); // center, radius thedrawing.add(aline); thedrawing.add(aline); thedrawing.add(acircle); thedrawing.draw(); // Referens (1) enjoytheartworkfor(2000); // milliseconds thedrawing.at(1).moveby(10, -10); // deltax, deltay thedrawing.at(1).rotate(90); // degrees around origin thedrawing.draw(); // Referens (2) C. Vad innebär följande designprinciper? Peka även ut minst ett ställe i lösningen där resp princip tillämpas, eller identifiera ifall den inte tillämpas i den här lösningen (2p) a) Single Responsibility Principle b) High Cohesion c) Low Coupling d) Single Choice Totalt 5p DFR/EJN/ND 130607 PS tentamen - facit Sidan 16 av 20

8. Lisp - Läs noggrant följande Lispkod:- (defun p (a b c) (list (list 'a a) (list 'b b) (list 'c c) ) ) (defun q (r s) (if (eql 'b (first (first r))) (cons (list 's (list (second (first r)) s)) (rest r)) (cons (first r) (q (rest r) s)) ) ) (setf b (p '(a b) '(c d) '(e f))) (q b 'b) (q b b) 1. Skriv ut resultatet från (q b 'b) 1p 2. Skriv ut resultatet från (q b b) 1p 3. Förklara stegvis och ingående hur funktion q fungerar. 3p Totalt 5p Note that b has value:- ((A (A B)) (B (C D)) (C (E F))) 1 ((A (A B)) (S ((C D) B)) (C (E F))) 2 ((A (A B)) (S ((C D) ((A (A B)) (B (C D)) (C (E F))))) (C (E F))) DFR/EJN/ND 130607 PS tentamen - facit Sidan 17 av 20

3 How does function q work? 1. (defun q (r s) 2. (if (eql 'b (first (first r))) 3. (cons (list 's (list (second (first r)) s)) (rest r)) 4. (cons (first r) (q (rest r) s)) 5. ) 6. ) Abstract Explanation Line 1: 2 formal parameters r and s Line 2: r must be a list whose first element is also a list so r is of the form ((x y) z) o (first r) is therefore (x y) o (first (first r)) is therefore x o X is compared with the literal symbol b o If the comparison is true, line 3 is executed o If the comparison is false, line 4 is executed Line 3: here we know that x is equal to the symbol b hence r is ((b y) z) where y and z have values o The rest of r is z --- (rest ((b y) z)) o The first of r is (b y) o The second of the first of r is therefore y o s is a formal parameter and therefore has a value o (list (second (first r)) s) therefore produces (y s) o (list s (list (second (first r)) s)) therefore produces (s (y s)) where the first s is a literal symbol and the second s has the value of the formal parameter s o These 2 results are cons:ed (cons (s (y s)) z) to give ( (s (y s)) z ) Line 4: o The first element in the list does not have the literal symbol b as its first element i.e. x!= b o Cons this element (x y) with q applied to the rest of r z and the value of the formal parameter s Note that the final value cannot be evaluated until the actual parameters are known See the example based explanation below. DFR/EJN/ND 130607 PS tentamen - facit Sidan 18 av 20

Example Based Explanation 1. (defun q (r s) 2. (if (eql 'b (first (first r))) 3. (cons (list 's (list (second (first r)) s)) (rest r)) 4. (cons (first r) (q (rest r) s)) 5. ) 6. ) The actual parameters in the call (q b b) are b is the list ((a (a b)) (b (c d)) (c (d f))) q is applied to b and b r which is the balue of the global variable b i.e. ((a (a b)) (b (c d) ) (c (e f))) s which is b i.e. the literal symbol b Line 2: (first r) is the list (a b) (first (first r)) is the atom a This is not equal to the literal b hence execute Line 4 Line 4: (first r) is the list (a (a b)) The application of q is on a new actual parameter The first actual paramenet is now the list ((b (c d)) (c (e f))) The second is the literal symbol b q is applied recursively so the process starts again Line 2: r is ((b (c d)) (c (e f))) so (first r) is the list (b (c d)) (first (first r)) is b which matches the literal symbol b Line 3: (second (first r)) is the list (c d) (list (second (first r)) s) gives the list ((c d) b) since the value of s is the literal symbol b This in turn is made into a list with the literal symbol s giving (s ((c d) b)) This is then consed with the (rest r) which is (c (e f)) to give ((s ((c d) b) (c (e f))) which is returned to the recursive application in Line 4 And consed with (a (a b)) to give the final result o ((a (a b)) (s ((c d) b)) (c (e f))) and check with clisp o ((A (A B)) (S ((C D) B)) (C (E F))) The second application of q uses b instead of b hence we could take b from ((A (A B)) (S ((C D) B)) (C (E F))) which was the first result (q b b) and change this to the value of B which was ((A (A B)) (B (C D)) (C (E F))) to give the result of (q b b) ((A (A B)) (S ((C D) ((A (A B)) (B (C D)) (C (E F))))) (C (E F))) Check with the actual result from clisp:- ((A (A B)) (S ((C D) ((A (A B)) (B (C D)) (C (E F))))) (C (E F))) QED! DFR/EJN/ND 130607 PS tentamen - facit Sidan 19 av 20

Bilaga A - Grammatik: Pascallik språk 1. [prog] ::= [prog header] [var part] [stat part] 2. [prog header] ::= program id ( input, output ) ; 3. [var part] ::= var [var dec list] 4. [stat part] ::= begin [stat list] end. 5. [var dec list] ::= [var dec] [var dec list] [var dec] 6. [var dec] ::= [id list] : [type] ; 7. [stat list] ::= [stat] [stat list] ; [stat] 8. [stat] ::= [assign stat] 9. [assign stat] ::= id := [expr] 10. [expr] ::= [term] [R1] 11. [R1] ::= e + [term] [R1] 12. [term] ::= [factor] [R2] 13. [R2] ::= e * [factor] [R2] 14. [factor] ::= ( [expr] ) [operand] 15. [type] ::= integer 16. [id list] ::= id [id list], id 17. [operand] ::= id number DFR/EJN/ND 130607 PS tentamen - facit Sidan 20 av 20