{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

m2-soln-fall11

# m2-soln-fall11 - CMSC330 Fall 2011 Midterm#2 Solutions 1(14...

This preview shows pages 1–3. Sign up to view the full content.

CMSC330 Fall 2011 Midterm #2 Solutions 1. (14 pts) OCaml Types and Type Inference Give the type of the following OCaml expressions: a. (2 pts) fun x -> [x;x;x] Type = ‘a -> ‘a list b. (3 pts) fun x y -> x y 2 Type = (‘a -> int -> ‘b) -> ‘a -> ‘b Write an OCaml expression with the following type: c. (2 pts) (int * int) list Code = [1, 2] or [(1,2)] d. (3 pts) (‘a -> int) -> int Code = fun x -> 1+(x y) or (fun y x -> 1+(x y)) z Give the value of the following OCaml expressions. If an error exists, describe it e. (2 pts) let x = 3 in let x = 5 in x+1 Value / Error = 6 f. (2 pts) let x = 4 in let x = x+6 in x+3 Value / Error = 13 2. (15 pts) OCaml higher-order & anonymous functions Using fold and an anonymous function, write a function pairUp which given an int list returns a int list list, where every pair of elements in the original list is now paired up in a list. The strings should be in the same order as the in the original list. You may assume the original list has an even number of elements (including 0). Your function must run in linear time. You may not use any library functions, with the exception of the List.rev function, which reverses a list in linear time. Solutions using recursion and/or helper functions will only receive partial credit. Examples: pairUp [] = [] pairUp [1;2] = [[1;2]] pairUp [1;2;3;4] = [[1;2];[3;4]] pairUp [1;2;3;4;5;6] = [[1;2];[3;4];[5;6]] let pairUp l = List.rev (fold (fun a h -> match a with [] -> [[h]] // empty a = 1 st elem | [x]::t -> [x;h]::t // a begins w/ 1 elem list, add to list | [x;y]::t -> [h]::a // a begins w/ 2 elem list, make new elem ) [] l) ;; // initial a = [] let rec fold f a lst = match lst with [] -> a | (h::t) -> fold f (f a h) t

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
3.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 5

m2-soln-fall11 - CMSC330 Fall 2011 Midterm#2 Solutions 1(14...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online