Skip to content

Instantly share code, notes, and snippets.

@harmeetsingh0013
Last active April 11, 2018 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmeetsingh0013/9429757db3f9f1834a1ae36c87877492 to your computer and use it in GitHub Desktop.
Save harmeetsingh0013/9429757db3f9f1834a1ae36c87877492 to your computer and use it in GitHub Desktop.
object Example1Semigroup extends App with Data {
trait Addable[T] {
def add(a: T, b: T): T
}
implicit val addInt = new Addable[Int] {
override def add(a: Int, b: Int): Int = a + b
}
implicit val addMoney = new Addable[Money] {
override def add(a: Money, b: Money): Money = {
Money(a.dollars + b.dollars + ((a.cents + b.cents) / 100),
(a.cents + b.cents) % 100)
}
}
// [V: Addable] is shothand of (implicit addable: Addable[A])
implicit def addMap[K, V: Addable] = new Addable[Map[K, V]] {
override def add(a: Map[K, V], b: Map[K, V]): Map[K, V] = {
a.foldLeft(b) {
case (acc, (x, y)) =>
acc + (x -> acc.get(x).map(implicitly[Addable[V]].add(_, y)).getOrElse(y))
}
}
}
def add[A: Addable](a: A, b: A)(implicit addable: Addable[A]): A = addable.add(a, b)
println(s"Salary credit in you account xxxxxxx ${add(balance, salary)}")
println(s"Salary transfer to all employees ${add(balances, salaries)}")
println(s"Your game marbles balance is: ${add(marbles, won)}")
}
// output
Salary credit in you account xxxxxxx Money(422,44)
Salary transfer to all employees Map(James -> Money(713,96), Jimmy -> Money(543,88))
Your game marbles balance is: Map(James -> 6, Jimmy -> 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment