CMSC330 Summer 2009 Quiz 2 Name: _________Answers________________________________ 1. Functional languages (4 points) a. Why is Ocaml considered a functional programming language? Focuses on expression evaluation with less emphasis on memory writes; has higher-order functions; heavy use of recursion, etc. b. Give one reason why someone might want to use a functional language over an imperative one. Your answer should not be along the lines “…because they are better at/like functional languages more…” Easier to parallelize code when there aren’t memory writes 2. What is a higher order function? That is, what can you do with higher order functions that you cannot do with “regular” functions? (2 points) First class variable; can be passed to or returned from a function3. Give the types (as Ocaml would) of the following expressions, or ERROR if there is an error: (7 points) a. [2;‘c’] _______________error – heterogenous types_________ b. (2,‘c’) _______________int * char_______________________ c. [1;2;3] _______________int list__________________________ d. (‘c’;“hello”)_______________error – tuple uses , not ; ____________ e. [[1;2;2];[2;3]]_____________int list list________________________ f. [[[1;2]];[2;3]]_____________error – not same level of nesting______ g. Printf.printf “%d” 3 __________unit__________________________ 4. Give the type of the following functions or ERROR if there is an error (4 points): a. let head l a = match l with [] -> (1,(1+a)) | _ -> (0,1) ;; ___’a -> int -> int * int________________________________________ b. let head l = match l with [] -> [] | _ -> (0,1) ;; ___error – does not return same type______________________ 5. Give the value of the following Ocaml expressions or ERROR if there is an error (5 points) a. let x = 3 in x::[] _____________[3]________________________ b. let x = 3 in x@[1;2;3] ___error – concat list operator expects 2 lists___c. List.map((fun z -> z + z),[1;2;3]) ____[2 ;4 ;6]_______________________________ d. let x = 2 in let y = 3 in x::y::[2;4;6]______[2;3;2;4;6]_____________________________ e. let list = [1;2;3] in match list with [] -> -1 | (h::t) -> if (h <> 3) then 0 else 1
View Full Document