



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The second midterm exam for cs164, a computer science course, held in fall 2007. The exam consists of four problems, each with multiple parts. The problems cover topics such as activation records, visitors in object-oriented programming, closures, and syntax-directed translation. Students are required to write their answers in the space provided on the exam and are given a specific time limit.
Typology: Exams
1 / 6
This page cannot be seen from the preview
Don't miss anything!




Problem 1: Activation Records [20 points] Part 1 [5 points]: Even a statically scoped language needs a dynamic link in its activation record. What purpose does the dynamic link serve? Answer: _____________________________________________ Part 2 [10 points]: Draw the configuration of the call stack at the point when this program reaches the print statement. Include in your figure: Dynamic links Static links Arguments Local variables You can ignore other content of the activation record. x = 0 function f() local x = 1 function g(n) local y = n if n>0 then g(n-1) else print(y*x) end end g(3) end f() Your answer: This is the stack. It grows upwards from the bottom. args locals SL DL
Problem 3: Closures [30 points] Part 1 [5 points]: What does the following program output? Answer: __, __, __, __ function f() local x = 1; return function () x = x+1; return x end end i1 = f() i2 = f() print(i1(), i2(), i1(), i2()) Part 2 [5 points]: How many copies of variable x are created during the execution of the above program? Answer: __ Part 3 [5 points]: Indicate (by drawing a ‘*’ sign) where in the code can these variable(s) be deallocated. Indicate the earliest point(s) where deallocation is safe. Continues on next page
Part 4 [15 points]: The Lua code below implements a list module (you have seen a similar code in the lecture). Your goal is to implement the function iterator() so that it can be used to iterate over the values of the list exactly as shown below. Use closures to implement the iterator functionality. Assume that the list is not modified while an iterator operates on it, but two iterators may simultaneously iterate over the same list. List = {} function List.new () return {first=0, last=0} end function List.push(list,value) list[list.first] = value list.first = list.first+ end function List.remove(list,value) if list.last >= list.first then return nil end local last = list.last list.last = list.last + 1 return list[last] end myList = List.new() List.push(myList, 1) List.push(myList, 2) List.push(myList, 3) next = List.iterator(myList) while true do element = next() if element == nil then break end print(element) -- outputs 1 2 3 end