Suggested Answers to Midterm 2
1) S -> abbb | aSbbbb
S
/|\
a S bbb
/ \
a bbb
2) a and b are using positional matching
c and d are using by-name (nominal) matching
output: 8 13 5 7
3) def filter(n,list)
i=0
ret = []
if ((list == []) | (n < 1))
ret
else list.each { |a| if ((i % n) == 0)
ret.push(a)
i+=1
else i+=1 end}
end
ret
end
4) ERROR: the value of "x" is undefined.
5) zippify: 'a -> 'b -> 'c -> ('a * 'b) -> 'c
scrunch: (('a * 'a list) -> 'a) -> 'a -> 'a list -> 'a
6) Access to an object is via its methods. The reference to the object just gives you a way to pass messages (call methods) on that object. So, how the object gets passed has no influence on whether it can be modified.
7)
class WC
@words = Array.new
@counts = Array.new
def count(w)
count = 0
@words.each_index { |i| if (@words.at(i) == w)
count = @counts.at(i) end }
count
end
def enter(w)
if (@words == nil)
@words = Array.new(1,w)
@counts = Array.new(1,1)
else @words.push(w)
@counts.push(1)
end
self
end
def inc(w)
@words.each_index { |i| if (@words.at(i) == w)
@counts[i] += 1 end }
self
end
end
8) Assume there is a function with a header (specification) like this:
void fun (int &first, int &second)
a) fun(total,total)
b) fun(list[i],list[j]) {when i = j}
or the following function header:
void fun1(int &first, int vector[])
c) fun1(list[i],list)
9) "it in style"