===== 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: case class Gradebook(book: Map[String,Int]) **8.1.1.** Add a method ''+'' to the class, which adds a new entry to the gradebook. def + (entry: (String, Int)): Gradebook = ??? **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. def setGrade(name: String, newGrade: Int): Gradebook = ??? **8.1.3.** Implement a method ''++'' which merges two gradebooks. You may assume the student entries are unique among the two gradebooks. def ++(other: Gradebook): Gradebook = ??? **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. 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. ??? } **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). def gradeNo: Map[Int,Int] = ??? ==== 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. Map(2 -> 2, 0 -> 3) // encodes 2*X^2 + 3 Add to your worksheet, the definition below: case class Polynomial (nonZeroTerms: Map[Int,Int]) **8.2.1.** Add a method ''*'' which multiplies the polynomial by a given coeficient: def *(n: Int): Polynomial = ??? **8.2.2.** Override the ''toString'' method to nicely display a polynomial: override def toString: String = ??? **8.2.3.** Implement a method ''hasRoot'' which checks if a given integer is a root of the polynomial. def hasRoot(r: Int): Boolean = ??? **8.2.4.** Implement a method ''+'' which adds a given polynomial to this one. Hint - this operation is very similar to gradebook merging. def +(p2: Polynomial): Polynomial = ???