|
| 1 | +package cm2 |
| 2 | + |
| 3 | +case class Person(name: String) |
| 4 | +case class Paper(title: String, authors: List[Person], body: String) |
| 5 | + |
| 6 | +class Viewers(val persons: Set[Person]) |
| 7 | + |
| 8 | +class ConfManagement(papers: List[Paper], realScore: Map[Paper, Int]) extends App { |
| 9 | + |
| 10 | + private def hasConflict(ps1: Set[Person], ps2: Iterable[Person]) = |
| 11 | + ps2.exists(ps1 contains _) |
| 12 | + |
| 13 | + type Viewable[T] = implicit Viewers => T |
| 14 | + |
| 15 | + def vs: Viewable[Viewers] = implicitly |
| 16 | + |
| 17 | + def viewers: Viewable[Set[Person]] = vs.persons |
| 18 | + |
| 19 | + def score: Paper => Viewable[Int] = |
| 20 | + paper => |
| 21 | + if hasConflict(viewers, paper.authors) then -100 |
| 22 | + else realScore(paper) |
| 23 | + |
| 24 | + def viewRankings: Viewable[List[(String, Int)]] = |
| 25 | + papers.sortBy(-score(_)).map(p => (p.title, score(p))) |
| 26 | + |
| 27 | + def delegate[T]: (Viewers => T) => Person => Viewable[T] = |
| 28 | + query => p => query(new Viewers(viewers + p)) |
| 29 | +} |
| 30 | + |
| 31 | +object Test extends App { |
| 32 | + def bob = Person("Bob") |
| 33 | + def peter = Person("Peter") |
| 34 | + def p1 = Paper("Bob's paper", List(bob), "") |
| 35 | + def p2 = Paper("Peter's paper", List(peter), "") |
| 36 | + |
| 37 | + implicit def __1: Viewers = new Viewers(Set(bob)) |
| 38 | + |
| 39 | + val cm = new ConfManagement(List(p1, p2), Map(p1 -> 2, p2 -> 3)) |
| 40 | + |
| 41 | + println(cm.viewRankings) |
| 42 | + println(cm.score(p1)) |
| 43 | + println(Orderings.isLess(Nil)(List(1, 2, 3))) |
| 44 | +} |
| 45 | + |
| 46 | +object Orderings extends App { |
| 47 | + |
| 48 | + trait Ord[T] { def less: T => T => Boolean } |
| 49 | + |
| 50 | + implicit def __1: Ord[Int] = new Ord[Int] { |
| 51 | + def less: Int => Int => Boolean = |
| 52 | + x => y => x < y |
| 53 | + } |
| 54 | + |
| 55 | + implicit def __2[T]: implicit Ord[T] => Ord[List[T]] = new Ord[List[T]] { |
| 56 | + def less: List[T] => List[T] => Boolean = |
| 57 | + xs => ys => |
| 58 | + if ys.isEmpty then false |
| 59 | + else if xs.isEmpty then true |
| 60 | + else if xs.head == ys.head then less(xs.tail)(ys.tail) |
| 61 | + else isLess(xs.head)(ys.head) |
| 62 | + } |
| 63 | + |
| 64 | + def isLess[T]: T => T => implicit Ord[T] => Boolean = |
| 65 | + x => y => implicitly[Ord[T]].less(x)(y) |
| 66 | + |
| 67 | + println(isLess(Nil)(List(1, 2, 3))) |
| 68 | + println(isLess(List(List(1)))(List(List(1)))) |
| 69 | +} |
0 commit comments