Skip to content

Instantly share code, notes, and snippets.

@harmeetsingh0013
Created April 11, 2018 18:12
Show Gist options
  • Save harmeetsingh0013/aa6e6d0dba923b70f07c761855a7f372 to your computer and use it in GitHub Desktop.
Save harmeetsingh0013/aa6e6d0dba923b70f07c761855a7f372 to your computer and use it in GitHub Desktop.
object Example4Semigroup extends App with Data {
implicit val moneySemigroup = new Semigroup[Money] {
override def combine(x: Money, y: Money): Money = {
Money(x.dollars + y.dollars + ((x.cents + y.cents) / 100),
(x.cents + y.cents) % 100)
}
}
import cats.instances.int._
import cats.instances.map._
def add[A: Semigroup](a: A, b: A)(implicit semigroup: Semigroup[A]): A = semigroup.combine(a, b)
println(s"Salary credit in you account xxxxxxx ${add(balance, salary)}")
println(s"Salary transfer to all employees ${add(balances, salaries)}")
// another way to call combine method with beautiful syntax using cats
import cats.syntax.semigroup._
println(s"Salary transfer to all employees ${balances |+| salaries}")
println(s"Your game marbles balance is: ${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))
// 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