m2-soln-fall10

# m2-soln-fall10 - CMSC330 Fall 2010 Midterm#2 Solutions 1(22...

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

CMSC330 Fall 2010 Midterm #2 Solutions 1. (22 pts) OCaml Types and Type Inference Give the type of the following OCaml expressions a. (2 pts) fun x y -> [x + y] Type = int -> int -> int list b. (3 pts) fun x y -> [x ; y] Type = ‘a -> ‘a –> ‘a list c. (3 pts) fun x y -> [x y] Type = (‘a -> ‘b) -> ‘a -> ‘b list Write an OCaml expression with the following type d. (2 pts) bool -> int Code = fun x -> if x then 1 else 2 e. (3 pts) bool -> int -> int Code = fun x y -> if x then y+1 else 2 f. (3 pts) (bool -> int) -> int Code = fun x -> (x true)+1 Give the value of the following OCaml expressions. If an error exists, describe it g. (2 pts) let x = 2 in let x = 4 in x+8 Value / Error = 12 h. (2 pts) let x = 2 in let y = x+4 in x+y Value / Error = 8 i. (2 pts) let x = 2 in let x = x+4 in x+8 Value / Error = 14 2. (12 pts) OCaml programming a. (8 pts) Implement a function generateFinder which when passed a list of strings wanted returns a function that takes a string name as argument, and returns true if name is in wanted . You are not allowed to use any OCaml library functions. Example: let findJedi = generateFinder [“Yoda”; “Luke”; “Obi-Wan”] ;; let findSith = generateFinder [“Palpatine”; “Vader”] ;; findJedi “Luke”;; (* returns true *) findJedi “Vader”;; (* returns false *) findSith “Vader”;; (* returns true *) let rec generateFinder lst name = match lst with [] -> false | (h::t) -> if (h=name) then true else (generateFinder t name) b. (4 pts) What feature of closures allows a simple solution to the problem above? Explain. The closure’s environment stores the value of variables, in this case the list of strings to

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

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

## This note was uploaded on 01/13/2012 for the course CMSC 330 taught by Professor Staff during the Fall '08 term at Maryland.

### Page1 / 5

m2-soln-fall10 - CMSC330 Fall 2010 Midterm#2 Solutions 1(22...

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

View Full Document
Ask a homework question - tutors are online