Due on: February 21st
In this lab we practice using ML lists and recursion to do complex computations.
1. Evaluate the following expressions in ML, and write down the result.
[7, 7 ] = [ 7 ];
[ 3, 4 ] = [ 4, 3 ];
[4, 8 ] ^ [0, 2, 3];
hd ([5, 6, 2, 3]);
tl ([5, 6, 2, 3]);
hd ([]);
tl ([]);
length ([]);
length ([1,2,3,6,1]);
List.nth ([1.3, 2.7, 5.0, 7.5], 2);
List.nth ([1.3, 2.7, 5.0, 7.5], 3);
List.take ([1.0, 2.0, 3.7, 8.2], 3);
List.take ([1.0, 2.0, 3.7, 8.2], 2);
What do List.nth and List.take functions do?
2. Write a function twosum(numlist: real list) that takes a list of four reals, and returns a two-element list of reals, which are the sum of the first and third elements, and the sum of the second and fourth elements, respectively. For example, twosum([1.0,2.0,1.0,4.0]) would return the list [2.0, 6.0] Use the built-in List.nth function to access the list elements. What happens if you call your function with a list of less than four elements? When having a fixed number of elements, is the tuple or the list a better structure to use? Why?
3. Write a function sumlists(list1:int list, list2:int list) that takes two lists of integers, and returns a list of integers where each element is the sum of the elements in the two input lists. For example, sumlists([1,2,3],[3,4,5]) should return [4,6,8]. Try to handle the case where the two lists are of different lengths (the output list would be the length of the longest input list, and the elements in it after the shorter list ran out would just be equal to the elements in the longer list).
4. Write the function findi(i:int, l:int list)
defined
in class. Extend the function findi so that
if i is larger than the lenght of the list, it returns
a -1.
How is the findi function
different from the List.nth function.
5. Program the Tower of Hanoi puzzle as discussed in class.
6. List elements do not just have to be simple values -- we can use tuples as list elements, for example. A list such as [(2,3.0),(5,4.4),(10,1.2)] is a 3-element list where each element is an int*real tuple (each list element must still be of the same type).
In this problem, we want to calculate the total mileage, total gasoline used, and our average miles per gallon for the whole trip. The trip is composed of a number of segments. So, our input is a list, each element is the mileage and gasoline used for one segment of the trip -- in an int*real tuple (the miles are just integers). You are to write a function mpg(trip: (int*real) list) that takes a list of miles*gallons tuples and returns an int*real*real tuple (a 3-tuple), of the total mileage, the total gasoline used, and the miles per gallon for the whole trip. You can (and should) define other functions to help you if you need to (hint: What are the first two values you have to return from this function? Perhaps you could write a function for each).