Document 10805478

advertisement
Long Quiz4 ( 45mins) Name: Person Number: C. [5marks]
Problem 1. (20pts) ogic of
Programming/ is correct. (Note: Only one of the answers
Indicate
which Lone
the followingProlog choices
correct.) Use “Answer Sheet: Part C” to indicate your answer.
C. [5marks]
What is the SWI-Prolog answer to the following queries?
of fthe
following
choices
is correct.
a) IIndicate
ndicate which
which one
of the ollowing choice is correct: (Note: Only one of the answers is
“Answer Sheet: Part C” to indicate your answer.
(1) correct.)
1. ?- Use
f(a,b) =.. [X,Y].
answer to the following queries?
What is the SWI-Prolog
a) X=a, Y=b
1. ?- f(a,b) =.. [X,Y].
b) X=f, Y=a
a) X=a, Y=b
c) X=f, Y=b
b) X=f, Y=a
d) No
c) X=f, Y=b
d) No
2. ?- assert(a(2)),assert(a(3)),retract(a(X)),write(X),write('
'),fail.
Ans: d) a) 2
(2) 2. ?- assert(a(2)),assert(a(3)),retract(a(X)),write(X),write('
'),fail.
No
a) 2
b)
No 2 3
Yes
b) 2 3
c)
Yes2 3
No
c) 2 3
No 3 2
d)
Yes
d) 3 2
Yes
3. ?- X is 5, fail.
Ans: c) fail.
3. ?- X is 5,
a) X =5
a) X =5Yes
Yes
b) No
b) No
c) Yes
c) Yes
d) none of the above
d) none of the above
No
d) 3 2
Yes
(3) 3. ?- X is 5, fail.
a) X =5
Yes
b) No
c) Yes
d) none of the above
Ans: b) 4. assert(a(1)),assert(a(2)),retract(a(X)),!,write(X),
write(' '),fail.
(4) CSI2165
Final Exam
Page 3 of 12
a)
1
2
Yes
b) 1 2
No
c) 2 1
No
d) 1
No
D. [20 marks]
Ans: d) Read the following programs and provide the answer to the query (only the first answer
that SWI-Prolog
wouldpproduce).
b) Please read following rograms and write down result that SWI-­‐Prolog would 5.
Given the following code (DCG):
produce). np --> adj, noun.
adj --> [red].
adj --> [blue].
prog_1(X,[X,_]).
1.
noun --> [book].
prog_1(X,[_|L]):-prog_1(X,L).
The Prolog
translation of these 4 DCG clauses is:
Program
np(A, B):- adj(A, C), noun(C, B).
adj([red|A], A).
adj([blue|A], A).
noun([book|A],
Query A). ?- prog_1(X,[a,b,c,d]).
What is the answer to the following query?
X =
Answer
?- np([red, book],R).
Ans: X = c a) No
b) R = []
Yes
c) R = [red, book]
2.
Program
prog_2(L,R) :- acc(L, 0, R).
acc([_],A,A).
acc([H|T],A,R):- A1 is A+H, acc(T,A1,R).
Query
Answer
Ans: R = 10 CSI2165 3.
Program
Query
Answer
Ans: R = c 4.
Program
prog_2([1,2,3,4,5],R).
R =
Final Exam
prog_3([X|_], 1, X).
prog_3([_|Xs], K, Y):- K > 1,
K1 is K-1,
prog_3(Xs,K1,Y).
?- prog_3([a,b,c,d],3,R).
R =
prog_4([H|_], H):- number(H), !.
prog_4([_|T], S):- prog_4(T,S).
Page 6 of 12
Models of Computation, 2010
2
yields a command, written while B do C .
We will study the operational semantics of While. However, we first study
the operational
semantics
of simple expressions
(without
prog_4([H|_],
H):- number(H),
!. variables), since it
4.
is helpful to introduce the
basic concepts of the operational semantics using
prog_4([_|T], S):- prog_4(T,S).
Program
such
terms.
simple
1.1
Operational
Semantics
for SimpleExp
?prog_4([a,b,4,d,3,a(b,c)],S).
Query
We
operational semantics for simple expressions without variables.
give the
S =
Answer
Ans: S = false Syntax of Simple Expressions
Problem 2. (20pts) Operational Semantics Assume we have following SimpExp ModelsCSI2165
of Computation, 2010
4 7 of 12
Final Exam
Page
Slide 2
E ∈ SimpleExp ::= n | E + E | E × E | ...
where n ranges over the numerals 0, 1, 2, .... We can add more
operations if we need to.
We work with abstract syntax (trees).
Please write down Big Step semantics for it. ( You can choose all notation system introduced in oSemantics
ur class) Big-step
of SimpleExp
Ans: (B-NUM)
Slide 4
n⇓n
Numbers v Numerals We distinguish between numerals, written
n, 0, 1, 2, ..., and E
the natural numbers, written n, 0, 1, 2, .... The natuE2 ⇓ n2
1 ⇓ n1
ral numbers (B-ADD)
are the normal numbers that we
life, while the
n3use
= n1in+everyday
n2
E
+
E
⇓
n
1 describing
2
3these numbers. We write n to denote
numerals are just syntax for
the
natural
number
represented
by
numeral
n
.
We
assume
that n = n,
We can give similar rules for multiplication and other natural
E1 add
" n1 numbers
E2 " ntogether
0 = 0, 1 = 1,..... We can
but not numerals. Instead,
2
operations.
(B ! MUL)
n3 = n1 # n2 we can write a program in Exp
the result of ‘adding a pair of
E1which
# E2 " computes
n3
numbers’.
distinction between numerals and numbers is subtle, but important, beThe
cause
it is one manifestation of the difference between syntax and semantics.
The difference should become clearer once we have studied the various seIntuitively, a rule such as
E1 ⇓ n1
E2 ⇓ n2
} aux[i]=aux[i]+1;
}}
} int max=0;
for(int
i=0;i<n;i++)
int
max=0;
if
(aux[i]>max)
for(int i=0;i<n;i++)
max=aux[i];
if (aux[i]>max)
Problem 3. (20pts) Omax+1;
bject – Oriented Programming return
max=aux[i];
} return max+1;
a) Consider t}he following Java program. 24.Consider
the following Java program.
class
A{
24.Consider the
following
Java program.
int
f()
class A { { return 1; }
} int f() { return 1; }
} class B extends A {
intBf()extends
{ returnA0;{ }
class
} int f() { return 0; }
} class Main {
public
void main(String[] args) {
class
Mainstatic
{
A
a
=
new
B();main(String[] args) {
public static void
System.out.println(a.f());
A a = new B();
} System.out.println(a.f());
} }
} What does this program print?
0
WhatOutput:
does this program print?
Ans: Output:
0 0
25.Consider
the following program.
class
Identthe { program.
25.Considerb) the
following
Consider following Java program. int
f(int
x)
class Ident { { return x; }
intf(int
g(intx)x){ return
{ returnx;f(f(x));
}
int
}
} int g(int x) { return f(f(x)); }
} class Square extends Ident {
class Square extends Ident {
12
int f(int x) { return x * x; }
12
}
class Main {
public static void main(String[] args) {
Ident a = new Ident();
Ident b = new Square();
Square c = new Square();
System.out.println(a.g(3) + " " + b.g(3) + " " + c.g(3));
}
}
What does this program print?
Output: 3 81 81
Ans: 3 3 3 26.Write
an
expression that will extract the substring "kap", given the following declaration:
String str = "kakapo";
String str1 = str.substring(2,5);
27. What will be the result of attempting to compile and run the following code?
class MyClass {
public static void main(String[] args) {
String str1 = "str1";
String str2 = "str2";
String str3 = "str3";
str1.concat(str2);
Problem 4. (20pts) Type Checking and Type Inference Answer each question below concisely. Use no more than a sentence or two, a picture, a simple equation, a judgement or a typing rule, etc. a) Give one brief reason or situation where strongly typed programming languages like ML or Java have an advantage over “weakly” typed languages like C. Ans: Strict enforcement of type rules with no exceptions. Incorrect type usage can be detected either at run time or at compile time. Strong typing catches more type errors than weak typing, resulting in fewer hard errors. In a strongly typed language, conversion between types requires the use of explicit conversion functions as opposed to implicit type coercion. b) Give one brief reason or situation where strongly typed programming languages like ML or Java have an advantage over languages that are not statically (i.e., compile-­‐time) typed at all like Scheme or Lisp or scripting languages like Perl, Python, Ruby, PHP, and JavaScript. Ans: The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time). c) What is the difference between a covariant subtyping rule and a contravariant subtyping rule? Ans: Contravariant rule: S is a subtype of T if:
1. S provides all the operations that T does (and maybe some more)
2. For each operation in T, the corresponding operation in S has the
same number of arguments and results
3. The types of the results of S's operations are subtypes of the types of
the corresponding results of T's operations
4. The types of the arguments of T's operations are subtypes of the
types of the corresponding arguments of S's operations (note the
reversal of T and S here)
N.B. If S=T, then S is a subtype of T.
Covariant rule:
same as above, except for 4:
1. The types of the arguments of S's operations are subtypes of the
types of the corresponding arguments of T's operations
d) When performing the type inference algorithm discussed in class, what part of the algorithm fails when you try to do type inference for this function: (fun id (x) = x x). Be as specific as possible. The best answer has this form: “During _______, ______ fails” Ans: During polymorphism, the function body fails infer what type the result will have. e) In ML, we can write down the following data type definition: datatype tree = Leaf of int | Node of int * tree * tree Using only int, recursive, sum and product types, encode this type. Ans: datatype tree = int * int list * int list f) Concisely describe the difference between an operational and a denotational semantics for a language. Ans: •
Denotational semantics is similar to high-­‐level operational semantics, except: o Machine is gone o Language is mathematics (lamda calculus) •
The difference between denotational and operational semantics: o In operational semantics, the state changes are defined by coded algorithms for a virtual machine o In denotational semantics, they are defined by rigorous mathematical functions g) Why might one choose to write down an operational semantics using “evaluation contexts” as opposed to the more standard way we did things at the beginning of class. Ans: because it is similar to the parsing process that we have gone through. h) Is this a reasonable subtyping rule: -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐ (for any well-­‐formed type t’) forall a. t <= t[t’/a] Yes or no? Why or why not -­‐-­‐ briefly? Hint: it might help to think about a specific example where t is a function type. Ans: No, in our course we consider function as many to one relationship . Problem 5. (20pts) Virtual Maching/Exception/Concurrency a) What is the result running following program ? class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } } public class FullConstructors { public static void f() throws MyException { System.out.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException { System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); } public static void main(String[] args) { try { f(); } catch(MyException e) { e.printStackTrace(); } try { g(); } catch(MyException e) { e.printStackTrace(); } } } Ans: Throwing MyException from f() MyException at FullConstructors.f(FullConstructors.java:13) at FullConstructors.main(FullConstructors.java:26) Throwing MyException from g() MyException: Originated in g() at FullConstructors.g(FullConstructors.java:19) at FullConstructors.main(FullConstructors.java:34) b) What is the result of following program ? class CircularSet { private int[] array; private int len; private int index = 0; public CircularSet(int size) { array = new int[size]; len = size; // Initialize to a value not produced for(int i = 0; i < size; i++) array[i] = -­‐1; } public synchronized void add(int i) { array[index] = i; index = ++index % len; } public synchronized boolean contains(int val) { for(int i = 0; i < len; i++) if(array[i] == val) return true; return false; } } public class SerialNumberChecker { private static CircularSet serials = new CircularSet(1000); static class SerialChecker extends Thread { SerialChecker() { start(); } public void run() { while(true) { int serial = 5; if(serials.contains(serial)) { System.out.println("Duplicate: " + serial); System.exit(0); } serials.add(serial); } } } public static void main(String[] args) { for(int i = 0; i < 10; i++) new SerialChecker(); } } Ans: none 
Download