F# Programming Assignment

CIS 580 Spring 2013

Due: Wednesday, February 27

Problems

Solve each of the following problems using only the features of F# that we have discussed in class. In particular, you will not receive credit for solutions that use imperative programming constructs, or predefined (built-in) functions that make the solutions completely trivial. If you have doubts about what is allowed, check with me.

For each problem, write a single function definition without any nested functions. Your solutions do not need to be tail recursive.

  1. Define a function called sum that takes a list of integers and returns their sum.
  2. Define a function called max that takes a list and returns the largest value in the list. You may assume that the list is not empty. Do not use the built-in List.max function.
  3. Define a function called zip that takes a pair (tuple) of equal length lists as a single parameter and returns a list of pairs. The first pair should contain the first element of each list, the second pair contains the second element of each list, and so on.
  4. Define a function called filter that takes a boolean function, f, and a list as arguments. The result should be a new list which contains just those elements, e, from the original list such that f(e) is true. Do not use the built-in List.filter function.

Examples

The following examples show how your functions should behave. If you have any doubt about the requirements, ask me.
> sum []
val it : int = 0

> sum [3]
val it : int = 3

> sum [2; 1; 3]
val it : int = 6

> sum [12; -3; 14; 87]
val it : int = 110

> max [89; 42; 112; 36; 90; -205]
val it : int = 112

> max [-5; 0; -12; -3]
val it : int = 0

> max ["c"; "a"; "p"; "f"]
val it : string = "p"

> zip ([1], [2])
val it : (int * int) list = [(1, 2)]

> zip (["a"; "b"; "c"; "d"; "e"], [1; 2; 3; 4; 5])
val it : (string * int) list = [("a", 1); ("b", 2); ("c", 3); ("d", 4); ("e", 5)]

> filter (fun x -> x > 10) [ 2; 12; 3; 23; 62; 8; 2 ]
val it : int list = [12; 23; 62]

> filter (fun x -> x%2 = 0) [ 2; 12; 3; 23; 62; 8; 2 ]
val it : int list = [2; 12; 62; 8; 2]

> filter (fun s -> s < "kangaroo") [ "pig"; "cow"; "horse"; "lion" ]
val it : string list = ["cow"; "horse"]

Hints:


Submissions

Please submit your function definitions in one F# source code file named "hw1.fs" as an email attachment to: pbergstein@umassd.edu. Use the subject line CIS-580 HW#2 in your email. Make sure your source file starts with a comment containing your name!