Skip to content

Instantly share code, notes, and snippets.

@harmeetsingh0013
Last active April 17, 2018 10:17
Show Gist options
  • Save harmeetsingh0013/b109e4c3a4b15f5d9a63575927c8c005 to your computer and use it in GitHub Desktop.
Save harmeetsingh0013/b109e4c3a4b15f5d9a63575927c8c005 to your computer and use it in GitHub Desktop.
object Example1Monoid extends App {
case class TwitterUser(username: String, followers: Int) extends Ordered[TwitterUser] {
override def compare(that: TwitterUser): Int = {
val c = this.followers - that.followers
if(c == 0) this.username.compareTo(that.username) else c
}
}
implicit val twitterUserMonoid = new Monoid[TwitterUser] {
override def empty: TwitterUser = TwitterUser("MinUser", Int.MinValue)
override def combine(x: TwitterUser, y: TwitterUser): TwitterUser = {
if(x.compareTo(y) >= 1) x else y
}
}
case class Max(user: TwitterUser) {
def +(usr: Max)(implicit m: Monoid[TwitterUser]): Max = {
Max(m.combine(this.user, usr.user))
}
}
val harmeetsingh = TwitterUser("singh_harmeet13", 132)
val knoldus = TwitterUser("knolspeak", 575)
val vikas = TwitterUser("vhazrati", 387)
val dzone = TwitterUser("dzone", 10640)
val scala = TwitterUser("scala_lang", 20421)
val winner: Max = Max(harmeetsingh) + Max(knoldus) + Max(vikas) + Max(dzone) + Max(scala)
println(s"Winner Is: $winner")
assert(winner.user == scala)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment