============================== Solutions to Minor ML homework ============================== 1. What are the values of the following expressions: 1. #2("bob", "paul", "susan") ==> "paul" 2. tl [2, 3, 4] ==> [3, 4] 3. tl([2, 3, 4]) ==> [3, 4] 4. implode([#"a", #"b", #"c]) ==> "abc" 5. hd (explode("Tom")) ==> #"T" 6. tl ("Tom" :: ["Bob", "Mary"]) ==> ["Bob", "Mary"] ----------------------------------------------------------------------- 2. What is wrong with each of the following expressions? 1. #4(3,4,5) This tuple doesn't have a 4th element. Possible fixes are #3(3,4,5) and #4(3,4,5,6). 2. #2([1,2,3]) ML interprets this as #2 on a list, which isn't valid. Try #2(1,2,3). 3. tl (tl (tl [1, 2])) Final call to tl is on an empty list, which isn't allowed. Remove a call to tl or add another element to the list. 4. implode(["a", "b", "c"]) Implode works on characters, not strings. Change to implode([#"a", #"b", #"c"]) 5. "Tom" :: ("Bob" :: "Mary") The cons operator takes an element and a list of elements of the same type, so the 2nd cons doesn't make sense. Try "Tom" :: ("Bob" :: ["Mary"]). 6. [1, "a", #"a"] Elements in a list need to have the same type. You could do this as a tuple: (1, "a", #"a"). ----------------------------------------------------------------------- 3. Write function declarations to compute the following: 1. Compute the length of a list fun len(L) = if null(L) then 0 else 1 + len(tl L); 2. Cycle a list once. fun cycle(nil) = nil | cycle(x::xs) = xs @ [x]; 3. Cycle a list the other way. fun cycleback(L) = if L = nil then nil else hd(rev(L)) :: rev(tl(rev(L))); 4. Remove all of the odd numbers for a list of integers. fun odd(x) = x mod 2 = 1; fun remove_odd(nil) = nil | remove_odd(x::xs) = if odd(x) then remove_odd(xs) else x :: remove_odd(xs); 5. Remove all vowels from a string. fun isvowel(c) = (c = #"a") orelse (c = #"A") orelse (c = #"e") orelse (c = #"E") orelse (c = #"i") orelse (c = #"I") orelse (c = #"o") orelse (c = #"O") orelse (c = #"u") orelse (c = #"U"); (* remove vowels for character lists *) fun remove_vowels_list(nil) = nil | remove_vowels_list(x::xs) = if isvowel(x) then remove_vowels_list(xs) else x :: remove_vowels_list(xs); (* handle string <--> character list conversion *) fun remove_vowels(L) = implode(remove_vowels_list(explode L)); (NOTE: the filter function could also be used for parts 4 and 5.) ----------------------------------------------------------------------- Bonus: Read in a file and return a list of characters in it. open TextIO; fun streamToCharList(ins) = if endOfStream(ins) then nil else explode(inputLine ins) @ streamToCharList(ins); fun fileToCharList(filename) = streamToCharList (openIn filename);