CSE341 Section #1 Problems Summary of ML features so far: types: int, real, bool, string, char, tuple, list, function Constructs: val = ; fun ( : , ..., : ) = ; if then else operator example description -------------------------------------------------------------------- + 2 + 2 addition - 18.4 - 3.8 subtraction * 3 * 18 multiplication / 14.5 / 3.4 real division div 88 div 10 integer (truncated) division mod 88 mod 10 modulus function ~ ~18 arithmetic negation ^ "hello" ^ "there" string concatenation :: 3 :: [1, 2, 3] construct a list from head/tail @ [1, 2] @ [3, 4] append two lists together < 4 < 19 less than > 2.4 > 3.8 greater than <= "ab" <= "cd" less than or equal >= 1.7 >= 4.7 greater than or equal = [1, 2] = [1, 1+1] equals <> 3 <> 4 not equal andalso 2 + 2 = 4 andalso 3 < 4 logical and (short circuited) orelse 8 > 9 orelse 1.4 < 2.8 logical or (short circuited) not not (8 < 9) logical negation Function Description -------------------------------------------------- abs absolute value of int or real real convert int to real floor/ceil integer just lower or higher than a real trunc/round convert real to int hd head (first element) of a list tl tail (elements after first) of a list length length of a list 1. What is the type of each of the following expressions? (3, 4.5) [4.5, 3.8] ((3, 4), 18.5) [[3, 4], [7]] [("hello", 3)] 2. For each of the following types, give an expression of that type: int * string * real string list int * string list (int * string) list (int * string) list list (int * string list) list 3. Write a function called gcd that returns the greatest common divisor of two integers. You can take advantage of the fact that: gcd(n, 0) = n for all n gcd(x, y) = gcd(x mod y, y) for all x, y Using the gcd function, write a function lcm that returns the least common multiple of two integers. 4. Write a function called sum that returns the sum of a list of integers. How would you change it to make it sum a list of reals? 5. Write a function called toReal that takes a list of ints as an argument and that returns the result of converting each int to a real. For example, toReal([3, 5, ~7]) should return [3.0, 5.0, ~7.0]. 6. Write a function called switchPairs that takes a list as an argument and that returns the list formed by switching the order of successive pairs of elements in the list. For example: switchPairs([3, 7, 4, 9, 8, 12]) should return [7,3,9,4,12,8] If the list has an odd number of values, then the final element should not be moved. For example: switchPairs([3, 7, 4, 9, 8, 12, 2]) should return [7,3,9,4,12,8,2]