CSC 123/252 Scary Test A scary test will make you study really hard for the real test. Give yourself about 40 minutes to complete the test. 1. Explain the difference between the F# functions f and g below: let f() = fun y -> let mutable x = 0 x <- x+y x let g() = let mutable x = 0 fun y -> x <- x+y x Determine the output of let f1 = f(2) let g1 = g(2) printfn "%d" (f1(1)+f1(1)); printfn "%d" (g1(1)+g1(1)); 1b. which of the above functions can be written in Gnu C? Explain. 2. Someone has invented a new language called C** that's claimed to be the best ever. The syntax certainly looks familiar: int x = 1; // declares and initializes global variable int f(int y) { return y+1; } // define function with argument y void MAIN() // MAIN must be in all capitals! { int x = 2; // declares "local" variable inside main stdout << f(x) << endl; // fantastic new way to print! // this will print 3 in C** } But you didn't find any documentation on whether this language uses static or dynamic scoping. Devise an experiment (write a program in C**) to find out. That is, write one program that will behave differently depending on the scoping rule. Be clear as to how to interpret the result of your experiment. 3. Explain why or why won't the following JAVA generic class compile class A { static T x; } // will this compile? 4. Explain why Object[] A = new String[4]; should or should not compile (regardless of whether it does) 5. Determine the output of the following Java program class A {} class B extends A {} public class goodquestion { public int f(A x) { return 1; } public int f(B x) { return 2; } public static void main(String[] args) { A n = new B(); goodquestion gq = new goodquestion(); System.out.println( gq.f(n) ); }//main } 6. Given the following definition of linked lists in F#: type List<'T> = Nil | Cons of 'T*List<'T>;; Write a tail recursive function to find the length of a list. 7. In F#, int(s) will convert string s into an integer and throw an exception if s can't be converted. 7a. Write a function `safeint` that returns a value of type `int option`: That is, Some(n) where n is an int, or None. The exception should be caught internally and not allowed to escape the function. Hint the syntax of a "try-with block" in F# is: try stuff with | e -> expression to return, must match type of "stuff" 7b. write a function that takes a string, calls safeint on the string, and either print the integer that was parsed or print "invalid input" if it can't be parsed. You're not allowed to call Option.get. 8. Given two Option objects a and b, explain what, if anything, is wrong with the following: a |> Option.map (fun x -> b |> Option.map (fun y -> x+y)) |> Option.iter (printfn "sum is %d") 9. Given type expr = Num of int | Times of expr*expr | Divide of expr*expr Write a function `eval` that evaluates an expr to an Option. Division by zero should result in None.