Tutorial 4 Find the Error
Total Page:16
File Type:pdf, Size:1020Kb
Tutorial 4 Find the error 1. let rec rotate n l = match n,l with 0,_ -> l |n,x::xs -> rotate (n-1) (xs@x) | _, _ -> failwith "rotate “ Error: This expression has type 'a but an expression was expected of type 'a list The type variable 'a occurs inside 'a list difference between the two funcLons 1. let rec rotate n l = match n,l with 0,_ -> l |n,x::xs -> rotate (n-1) (xs@[x]) | _, _ -> failwith "rotate " • rotate 3 [1;2;3;4;5]= = [4;5;1;2;3] 2. let rec rotate n l = match n,l with 0,_ -> l |n,x::xs -> rotate (n-1) xs@[x] | _, _ -> failwith "rotate " • rotate 3 [1;2;3;4;5]=[4;5;3;2;1] :: VS @ • For each of the following expressions, specify 1. If it is valid or not 2. The result list 3. The length of the result list :: VS @ ①[3] @ [4] ①int list = [3; 4] , length=2 ②3 @ 4 ②Invalid ③[3; 4] @ [] ③int list = [3; 4] , length=2 ④[3; 4] :: [] ④int list list = [[3; 4]] , length=1 ⑤[3] :: 4 ⑤Invalid ⑥3 :: [4] ⑥int list = [3; 4] , length=2 ⑦[] @ [[3]; [4]] ⑦int list list = [[3]; [4]] , length=2 ⑧[] :: [[3]; [4]] ⑧int list list = [[]; [3]; [4]] ,length=3 PracLce funcLon1 • Write a funcLon sum that takes a list and returns another list which sums the first element of the list with the last element and the second element of the list with the second to last element and so on. • Example • Sum [1]=[2] • Sum [1;2;4;7]=[8;6] • Sum [1;2;5]=[6;4] • let rec sum l= match l with • |[]->[] • |[x]->[x+x] • |x::xs-> ( • match List.rev(xs) with • |y::ys -> x+y::sum (List.rev(ys)) • |_ ->failwith "sum” );; PracLce funcLon 2 • A funcLon takes in a sorted list, and removes any duplicates. – As the list is sorted, any duplicates would be next to each other let rec uniq list = • match list with • [] -> [] • | h1 :: [] -> h1 :: [] • | h1 :: h2 :: tail -> if h1 = h2 • then uniq (h2 :: tail) • else h1 :: uniq (h2 :: tail);; WEEK 4 ASSIGNMENTS E1 • Write a funcLon that checks whether an element is a member of a list. • member : 'a -> 'a list -> bool • For example, • member 2 [1; 2; 3] = true • member 7 [1; 2; 3; 4] = false • member 'a' [ ] = false E1 • let rec member x = funcLon • | [] -> false • | h::t -> x == h || member x t;; E2 • Write a funcLon • prefix : 'a list -> 'a list -> bool • which returns true if the first argument is a prefix of the second argument. For example: • prefix [] [1; 2; 3] = true • prefix [1] [1; 2; 3] = true • prefix [1; 3] [1; 2; 3] = false E2 • let rec prefix xs ys = match xs, ys with • | [], _ -> true • | _, [] -> false • | (h::t), (h'::t') -> h == h' && prefix t t';; P • Write a funcLon which returns all the prefixes of a list (as a list of lists). • prefixes : 'a list -> 'a list list • For example • prefixes [1; 2; 3] = [[]; [1]; [1; 2]; [1; 2; 3]] P • let rec prefixes' p = funcLon • | [] -> [p] • | h::xs -> p::prefixes' (p @ [h]) xs;; • let prefixes xs = prefixes' [] xs;; .