Edit this page Backlinks This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ===== L08. Maps in Scala ===== ==== 8.1. Gradebooks as maps ==== We represent a gradebook as a map which holds, for each student (encoded as String), its grade (an Int). We implement a gradebook as a case class, as follows: <code scala> case class Gradebook(book: Map[String,Int]) </code> **8.1.1.** Add a method ''+'' to the class, which adds a new entry to the gradebook. <code scala> def + (entry: (String, Int)): Gradebook = ??? </code> **8.1.2.** Add a method ''setGrade'' which modifies the grade of a given student. Note that your method should return an updated gradebook, not modify the current one, since the latter is immutable. <code scala> def setGrade(name: String, newGrade: Int): Gradebook = ??? </code> **8.1.3.** Implement a method ''++'' which merges two gradebooks. You may assume the student entries are unique among the two gradebooks. <code scala> def ++(other: Gradebook): Gradebook = ??? </code> **8.1.4.** Lift the previous assumption by also considering the situation where a student may be part of the two gradebooks. Take the higher of the two grades. <code scala> def ++(other: Gradebook): Gradebook = { // the best strategy is to first implement the update of an entry into an existing Map... def updateBook(book: Map[String,Int], pair: (String,Int)): Map[String,Int] = ??? // and then use a fold to perform updates for all pairs of the current map. ??? } </code> **8.1.5.** Write a function which returns a map, containing as key, each possible grade (from 0 to 10) and a value, the **number** of students having that grade. (Hint: follow the same strategy as for the previous exercise). <code scala> def gradeNo: Map[Int,Int] = ??? </code> ==== 8.2. Polynomials ==== Consider a polynomial encoded as a map, where each present key denotes a power of X, and a value denotes its coefficient. <code scala> Map(2 -> 2, 0 -> 3) // encodes 2*X^2 + 3 </code> Add to your worksheet, the definition below: <code scala> case class Polynomial (nonZeroTerms: Map[Int,Int]) </code> **8.2.1.** Add a method ''*'' which multiplies the polynomial by a given coeficient: <code scala> def *(n: Int): Polynomial = ??? </code> **8.2.2.** Override the ''toString'' method to nicely display a polynomial: <code scala> override def toString: String = ??? </code> **8.2.3.** Implement a method ''hasRoot'' which checks if a given integer is a root of the polynomial. <code scala> def hasRoot(r: Int): Boolean = ??? </code> **8.2.4.** Implement a method ''+'' which adds a given polynomial to this one. Hint - this operation is very similar to gradebook merging. <code scala> def +(p2: Polynomial): Polynomial = ??? </code>