

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Exercise 1 There are two cases to consider:
Exercise 3 When the following f function is evaluated, a divide-by-zero runtime exception occurs. This shows that the actual parameter 1 div 0 passed to g is evaluated, even though f never uses the corresponding formal parameter. By-name parameter passing does not evaluate an actual parameter if the corresponding formal parameter is unused, so that cannot be how ML passes parameters. fun g(x,y) = y; fun f() = g(1 div 0, 0); Exercise 4 In the following code, the function testcalls(p,i) takes a list of integers p and an integer i, and makes i recursive calls passing p. Each call accesses the head of p (to try to make sure the compiler doesn't optimize the parameter away), and the calls are not tail calls (to try to make sure the compiler actually produces function calls with parameter passing), and the parameter is changed on each call (to try to make sure the compiler does not treat the list as a loop invariant). So if list parameters are copied on calls, testcalls(L,n) for fixed n should take time proportional to the length of L. In fact, by experimenting with testcalls we see that it takes time that is independent of the length of L: whether with val L = repeatedlist(1,1) or with val L = repeatedlist(1,100000), testcalls(L,2000000) takes the same amount of time. (This experiment is good evidence that our ML does not copy lists when passed as parameters. But no such experiment can be perfect when the compiler is treated as a black box. It is just possible, though unlikely, that the compiler is smart enough to notice that testcalls(L,n) = (hd L)*n, and so optimizes the entire execution away!) fun repeatedlist(,0) = [] | repeatedlist(e,i) = e::repeatedlist(e,i-1); fun testcalls(,0) = 0 | testcalls(p,i) = (hd p)+testcalls((hd p)::p,i-1); Exercise 6 a. A[0] = 0 and A[1] = 2 b. A[0] = 3 and A[1] = 2 c. A[0] = 3 and A[1] = 2, or A[0] = 1 and A[1] = 2, depending on the order in which the value-result parameters are written back after the call d. A[0] = 1 and A[1] = 3