This is an old revision of the document!


4.1. Common list operations

4.1.1. Write a function which returns true if a list of integers has at least k elements. Use patterns.

def atLeastk(k: Int, l: List[Int]): Boolean =
  if (k == 0) ???
  else ???
  }

4.1.2. Write a function which returns the first n elements from a given list. The function should not be implemented as tail-recursive.

def take(n: Int, l: List[Int]): List[Int] = ???
//take(3,List(1,2,3,4,5)) = 3

4.1.3. Write a function which drops the first n elements from a given list. The function should not be implemented as tail-recursive.

def drop(n: Int, l: List[Int]): List[Int] = ???
//drop(3,List(1,2,3,4,5)) = List(4,5)

4.1.4. Write a function which takes a predicate p: Int ⇒ Boolean, a list l and returns a sublist of l containing those elements for which p is true. The function should be curried.

def takeP(p: Int => Boolean)(l: List[Int]): List[Int] = ???
//takeP(_%2 == 0)(List(1,2,3,4,5,6)) = List(2,4,6)

4.1.5. Write a function which uses a predicate to partition (split) a list.

def part(p: Int => Boolean)(l: List[Int]): (List[Int], List[Int]) = ???
// part(_%2 == 0)(List(1,2,3,4,5,6)) = (List(2,4,6),List(1,3,5))

4.2. Gradebooks

More general implementation of taken, dropn and part are already implemented in Scala and can be used as member functions of lists. Examples are shown below:

val l = List(1,2,3,4,5,6,7,8,9)
l.take(3)
l.drop(3)
l.partition(_%2 == 0)

In what follows, we shall encode a gradebook as a list of pairs (<name>,<grade>), where <name> is a String and <grade> is an Int. Example:

val gradebook = List(("G",3), ("F", 10), ("M",6), ("P",4))

To make the type signatures more legible, we can introduce type aliases in Scala:

type Gradebook = List[(String,Int)] //the type Gradebook now refers to a list of pairs of String and Int

Add this type alias to your code before solving the following exercises.

4.2.1. Write a function which adds one point to all students which have a passing grade (>= 5), and leaves all other grades unchanged.