This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CS 421, Fall 2007 Sample Final Questions & Answers You should review the questions from the sample midterm exams, the real midterm exams, and the homework, as well as these question. 1. Write a function get primes : int > int list that returns the list of primes less than or equal the input. You may use the builtin functions / and mod . You will probably want to write one or more auxiliary functions. Remember that 0 and 1 are not prime. Answer: let rec every p l = match l with > true  x::xs > p x && every p xs let not_divides n q = ((q = 0)  not(n mod q = 0)) let rec get_primes n = match n with 0 >  1 >  _ > let primes = get_primes (n1) in if every (not_divides n) primes then n::primes else primes 2. Write a tailrecursive function largest: int list > int option that returns Some of the largest element in a list if there is one, or else None if the list is empty. Answer: let rec largest_aux lgst list = match list with > lgst  x :: xs > match lgst with None > largest_aux (Some x) xs  Some l > largest_aux (if l > x then lgst else (Some x)) xs let largest = largest_aux None (* I would also accept *) let largest list = List.fold_left (fun lgst x > match lgst with None > Some x  Some l > if l > x then lgst else Some x) None list 3. Write a function dividek n lst k , using Continuation Passing Style (CPS), that divides n successively by every number in the list, starting from the last element in the list. If a zero is encountered in the list, the function should pass 0 to k immediately, without doing any divisions . 1 # dividek 6 [1;3;2] report;; Result: 1 : unit = () Answer: let rec dividek n lst k = let rec dividek_aux n list inck = match list with > inck n  0::xs > k 0  x::xs > dividek_aux n xs (fun r > inck (r/x)) in dividek_aux n lst k 4. a. Give the types for following functions (you dont have to derive them): let first lst = match lst with  a:: aa > a;; let rest lst = match lst with  >  a:: aa > aa;; Answer: first : list rest : list list b. Use these types (i.e., start in an environment with these identifiers bound to these types) to give a type derivation for: let rec foldright f lst z = if lst = then z else (f (first lst) (foldright f (rest lst) z)) in foldright (+) [2;3;4] 0 Answer: let rec foldright f lst z = if lst = then z else (f (first lst) (foldright f (rest lst) z)) in foldright (+) [2;3;4] 0 Because of space constraints the proof tree has been broken up into four parts. Let = { first : list , rest : list list } , and = { foldright : ( ) ( list) , f : , lst : list , z : } ....
View Full
Document
 Fall '08
 Kamin

Click to edit the document details