Programming Languages and Techniques Final Exam, May 3 ..., Summaries of Programming Languages

CIS 120 — Programming Languages and Techniques. Final Exam ... A sample ASM (from lecture 28) ... Create at least four new test cases with examples of.

Typology: Summaries

2022/2023

Uploaded on 05/11/2023

paperback
paperback 🇺🇸

4.8

(12)

263 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CIS 120 Programming Languages and Techniques
Final Exam, May 3, 2011
Answer key
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Programming Languages and Techniques Final Exam, May 3 ... and more Summaries Programming Languages in PDF only on Docsity!

CIS 120 — Programming Languages and Techniques

Final Exam, May 3, 2011

Answer key

  1. Dynamic Dispatch Consider the following Java class definitions:

class A { private int x; public A (int x0) { x = x0; } public int getX () { return x; } } class B extends A { private int x1; private int y; public B (int x0, int y0) { super (x0 + 1); x1 = x0; y = y0; } public int getX() { return x1; } public int getY() { return y; } }

(a) (12 points) For each of the following variable declarations and initializations, list the static type of the variable and the dynamic class of the object referred to by that variable. If the initialization is invalid, write “INVALID” in both blanks. Assume that these statements occur in order, and that INVALID initializations do not prevent subsequent lines from referring to the variable.

A a1 = new A(3); Static: A Dynamic: A B b1 = a1; INVALID: B INVALID: A B b2 = new B(3,3); Static: B Dynamic: B A a2 = b2; Static: A Dynamic: B A a3 = new Object(); INVALID: A INVALID: Object Object o1 = new B(2,3); Static: Object Dynamic: B

Grading scheme: 1 point per blank. If they misread and put the correct static type for the two INVALIDs, do not count off.

(c) (5 points) Briefly define the terms “static type” and “dynamic class” in Java. How are they related?

Answer: The dynamic class of an object is the class that the object was created from. The static type of a variable or expression is the type declared by the programmer or calculated by the type checker. The static type of a variable is a supertype of the dynamic classes of every object that can be stored in that variable. Grading scheme: 2 points each for definition of static type and dynamic class. 1 point for saying that static type is a supertype of the dynamic class.

(d) (5 points) Briefly describe how the ASM model determines what code to put on the workspace at a method call. Answer: The Java ASM uses dynamic dispatch for method calls. Dynamic dispatch means that the code (e.g. method body) that is executed depends on the dynamic class of the object. The dynamic class is stored in the heap as part of the object. Methods are stored in the class table, if the method is not in the object’s class, then the ASM looks in the superclasses. Grading scheme: 2 points for stating that the code executed depends on the dynamic class of the object. 1 point for saying dynamic class is stored in the heap as part of the object. 1 point for saying that methods are retrieved from the class table. 1 point for describing method lookup.

  1. First-class functions

(a) (5 points) Recall the OCaml function map:

let rec map (f : ’a -> ’b) (l : ’a list) : ’b list = begin match l with | [] -> [] | (x :: xs) -> (f x) :: map f xs end

What is the value of the following OCaml expression?

map (fun (x : int) -> (x,x+1)) [1;3;5]

Answer : [(1,2);(3,4);(5,6)] Grading scheme: 5 points total.

  • full points for slightly confused syntax such as ((1,2),(3,4),(5,6)) or [[1,2],[3,4],[5,6]].
  • 4 points if the shape is correct, but the numbers are wrong, such as [(2,1);(4,3);(5,6)]
  • 3 points for not pairing but having all of the numbers, such as [ 1;2;3;4;5;6 ] or (1,2,3,4,5,6).
  • 2 points for 3 element lists [1;3;5] or [2;4;6]
  • 1 point for any other list

(b) (5 points) Now consider this OCaml function:

let rec foo (g : ’a -> ’a) (x : ’a) (n : int) : ’a = if n <= 0 then x else foo g (g x) (n-1)

What is the value of the following OCaml expression?

foo (fun (x : string list) -> "a" :: x) ["b"] 2

Answer : ["a"; "a"; "b"] grading scheme: 5 points total.

  • full points for slightly confused syntax such as [a,a,b] or ("a"; "a"; "b")
  • 4 points if the shape is correct, but the strings are wrong. (Too many/too few a’s.) ["a";"b"] or ["a";"a";"a";"b"] or ["a";"a"]
  • 3 points if the strings are correct but the shape is wrong such as [["a";"a"];"b"]
  • 2 points for any list composed of a’s and b’s
  • 1 point for any other list

(b) let rec in_t (t : ’a tree) : ’a list = begin match t with | Empty -> [] | Node (t1,a,t2) -> (in_t t1) @ [a] @ (in_t t2) end in in_t example_tree

Circle the result of this program.

[1; 2; 3; 4; 5; 6; 7]

[4; 2; 1; 3; 6; 5; 7]

[7; 6; 5; 4; 3; 2; 1]

[1; 3; 2; 5; 7; 6; 4]

(c) let rec post_t (t : ’a tree) : ’a list = begin match t with | Empty -> [] | Node (t1,a,t2) -> (post_t t1) @ (post_t t2) @ [a] end in post_t example_tree

Circle the result of this program.

[1; 2; 3; 4; 5; 6; 7]

[4; 2; 1; 3; 6; 5; 7]

[7; 6; 5; 4; 3; 2; 1]

[1; 3; 2; 5; 7; 6; 4]

(d) let rec no_t (t : ’a tree) : ’a list = begin match t with | Empty -> [] | Node (t1,a,t2) -> (no_t t1) @ (no_t t2) end in no_t example_tree

Write the result of this program. Answer: []

  1. Program Design Use the four-step design methodology to implement a Java method, called isAlmostCorrect, which determines whether a Word is almost correctly spelled. A word is almost correct if it is either already correct, or could be made to be correct by swapping two adjacent letters. For example, the word “cat” is almost correct. However, the word “cta” is also almost correct because it is one swap away from “cat”. However, the word “tac” is not almost correct because there is no way to swap two adjacent letters to form a correctly spelled word. The design process that we have been using this semester has four steps and you should use them to solve this design problem.

(a) (0 points) Step 1 is understanding the problem. You don’t have to write anything for this part—your answers below will demonstrate whether or not you succeeded with Step 1.

(b) (4 points) Step 2 is formalizing the interface. The first part of formalizing the interface is to understand the interfaces of the classes that this method should interact with. The argument to isAlmostCorrect should be an instance of the class Word, which represents sequences of letters. This class has the following interface:

public class Word { // Construct a word from the given string. If the argument string // contains nonletter characters (such as spaces or punctuation), // this constructor throws an InvalidArgumentException public Word (String w) { ... }

// Return the number of letters in the word public int length() { ... }

// Return a new word that exchanges the positions of the characters // at indices i and i+1. // For example, new Word("cta").swapAt(1) returns the word "cat" // // throws IllegalArgumentException when i is out of range // (i.e. not 0 <= i < length()-1 ) public Word swapAt(int i) { ... }

// Compare two words ignoring their case public boolean equals(Object o) { ... }

// Determine the ordering between words, ignoring their case public int compareTo(Object o) { ... } }

The method isAlmostCorrect should be a member of the class Dictionary. This class contains a set of correct words, a constructor, and isAlmostCorrect. The declarations for these class members are at the top of the next page.

(d) (12 points) Step 4 is implementing the program. Implement the isAlmostCorrect method to complete the design. For reference, documentation for the Java Collections class TreeSet appears in the Appendix. Answer:

boolean isAlmostCorrect(Word word) { if (word == null) { throw new InvalidArgumentException(); } if (dict.contains(word)) { return true; } for (int i=0; i < word.length()-1; i++) { Word n = word.swapAt (i); if (dict.contains(n)) { return true; } } return false; }

Grading scheme: 1 point per part unless otherwise stated

  • detect null input
  • do what their interface says for null
  • check if word already in dictionary
  • return true for already correct word
  • loop through positions in word
  • correct initial condition for loop (i=0)
  • correct termination condition for loop (i=length - 1)
  • increment index by 1
  • call swapAt
  • check result of swapAt in dictionary
  • return true if found
  • return false if not found

Ignore any attempts to to handle capitalization.

Linked data structures The next few questions concern an implementation of mutable queues in Java. The classes Queue, QueueNode, and EmptyQueueException are shown in the Appendix. This implementation is a slight variant of the code that we discussed in class and lecture, so read through the classes now before continuing on to the problems below.

  1. (10 points) Circle the result of each of the following code snippets.

(a) Queue q = new Queue(); q.enq("a"); q.enq("b"); System.out.println(q.deq());

prints a prints b does nothing

throws NullPointerException throws EmptyQueueException

(b) Queue q1 = new Queue(); Queue q2 = new Queue(); q1.enq("a"); q2.enq("b"); q1.deq(); System.out.println(q1.deq());

prints a prints b does nothing

throws NullPointerException throws EmptyQueueException

(c) Queue q1 = new Queue(); Queue q2 = q1; q1.enq("a"); q2.enq("b"); q1.deq(); System.out.println(q1.deq());

prints a prints b does nothing

throws NullPointerException throws EmptyQueueException

  1. The next two parts ask you to extend the Java Queue class shown in the Appendix with a new method, called insert. The method insert(n,v) inserts an element v into the nth^ position of the queue. To do so, it should create a new queue node containing v and add it into the queue so that it occurs at position n, where the head is at position 0. If n is a negative number, then the new element should be inserted at the beginning of the queue. If n is larger than the size of the queue, then the new element should be inserted at the end of the queue.

(a) (8 points) Briefly describe four test cases for the insert method. You don’t have to give the complete code for these test cases, just describe what they should test in words. Answer: potential tests include

  • Insert at position 0 to an empty queue
  • Insert at position < 0 to an empty queue
  • Insert at position ≤ 0 to any queue
  • Insert at position 0 to a nonempty queue
  • Insert at an interior position to a nonempty queue
  • Insert at the last position of a nonempty queue
  • Insert a null item in the queue

Grading scheme, 1 point each

(b) (14 points) Now implement the insert method.

public void insert(int n, E v) {

if (head == null || n <= 0) { head = new QueueNode(v, head); if (head == null) { tail = head; } } else { QueueNode cursor = head;

for(int i = 1; i < n && cursor.next != null; i++) { cursor = cursor.next; }

cursor.next = new QueueNode(v,cursor.next);

if (tail == cursor) { tail = cursor.next; } }

Grading scheme: 1 point for each item

  • detecting when the queue is empty
  • correct behavior when n < 0
  • detecting when inserting at beginning of queue
  • creating new queuenode to insert
  • assigning to head when inserting at beginning (*)
  • updating tail to alias head when queue is empty (*)
  • creating a cursor
  • loop moving the cursor
  • correct initial condition of loop
  • termination condition of loop (found the spot)
  • termination condition of loop (end of the queue)
  • detecting when adding to the end of queue (*)
  • updating tail when adding to end of queue (*)
  • not losing any existing elements in the queue

Starred items may be replaced with enq in some solutions.

For Reference: Documentation for class java.util.TreeSet

class java.util.TreeSet

boolean add(E e) Adds the specified element to this set if it is not already present. Returns true if the set did not already contain the specified element.

boolean contains(Object o) Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null? e==null : o.equals(e)).

boolean isEmpty() Returns true if this set contains no elements.

int size() Returns the number of elements in this set.

boolean remove(Object o) Removes the specified element from this set if it is present. Returns true if the set contained the specified element.

Sample Java ASM with Class Table (from Lecture 28)

For Reference: Queue, EmptyQueueException and QueueNode

The logic of these classes is the same as the code presented in class. The differences are (a) there is no division between the Queue interface and the QueueImpl implementation (b) deq throws an exception when called on an empty queue (c) fields in QueueNode are public, there are no getter or setter methods.

/** Nodes in the linked list */ class QueueNode { public E v; public QueueNode next;

public QueueNode(E v0, QueueNode next0) { v = v0; next = next0; } }

/** Thrown when deq invoked on an empty queue. */ class EmptyQueueException extends RuntimeException { }

class Queue {

/** A reference to the first node in the queue */ private QueueNode head; private QueueNode tail;

/** Create an empty queue */ public Queue() { head = null; tail = null; }

/** isEmpty() is true when the list has no elements */ public boolean isEmpty() { return head == null; }

public void enq(E x) { QueueNode newnode = new QueueNode(x, null); if (tail == null) { head = newnode; tail = newnode; } else { tail.next = newnode; tail = newnode; } }

Outline of the Java Paint program.

Most of the method implementations are not shown, and are replaced with....

public interface Shape { public void draw(Graphics2D gc); }

public class PointShape implements Shape { ... } public class LineShape implements Shape { ... }

public class Paint { /** Area of the screen used for drawing */ private Canvas canvas;

/** Current drawing color */ private Color color = Color.BLACK;

/** Strokes for drawing shapes with thin/thick lines */ public final static Stroke thinStroke = new BasicStroke(1); public final static Stroke thickStroke = new BasicStroke(3);

/** Current drawing thickness */ private Stroke stroke = thinStroke;

/** Available modes for user input */ public enum Mode { PointMode, LineStartMode, LineEndMode, }

/** Current drawing mode */ private Mode mode = null;

/** Location of the mouse when it was last pressed. */ private Point modePoint;

/** The list of shapes that will be drawn on the canvas. */ private LinkedList actions = new LinkedList();

/** an optional shape for preview mode */ private Shape preview;

private class Canvas extends JPanel { public Canvas(){ ... { public void paintComponent(Graphics gc) { ... } public Dimension getPreferredSize() { ... } }

/** Code to execute when the button is pressed while the mouse

  • is in the canvas. */ private class Mouse extends MouseAdapter { public void mousePressed(MouseEvent arg0){ ... } public void mouseDragged(MouseEvent arg0) { ... } public void mouseReleased(MouseEvent arg0) { ... } }

/** Create the toolbar containing radio buttons for the input modes as well as the thickness checkbox, Undo and Quit buttons */ private JPanel createModeToolbar(final JFrame frame) { ... }

/** Create the color toolbar */ private JPanel createColorToolbar() { ... }

/** Creates the main application window, assembles the user interface and displays it. */ public Paint () { final JFrame frame = new JFrame(); frame.setLayout(new BorderLayout());

canvas = new Canvas(); Mouse mouseListener = new Mouse(); canvas.addMouseMotionListener(mouseListener); // dragged events canvas.addMouseListener(mouseListener); // press/release events frame.add(canvas, BorderLayout.CENTER);

JPanel pane = new JPanel(); pane.setLayout(new GridLayout(2,1)); frame.add(pane, BorderLayout.PAGE_END); pane.add(createModeToolbar(frame)); pane.add(createColorToolbar());

frame.pack(); frame.setVisible(true); }

/** Entry point for the Paint application. */ public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { new Paint(); } }); }

}