Skip to content

Instantly share code, notes, and snippets.

@harmeetsingh0013
Created April 15, 2018 05:27
Show Gist options
  • Save harmeetsingh0013/c622085b8209c699eb173dba078eb4a4 to your computer and use it in GitHub Desktop.
Save harmeetsingh0013/c622085b8209c699eb173dba078eb4a4 to your computer and use it in GitHub Desktop.
import cats.kernel.Monoid
object Example1Monoid extends App with Data {
implicit val moneyMonoid = new Monoid[Money] {
override def empty: Money = Money(0, 0)
override def combine(x: Money, y: Money): Money = {
Money(x.dollars + y.dollars + ((x.cents + y.cents) / 100),
(x.cents + y.cents) % 100)
}
}
val lastYearExpenses = List(Money(3, 4), Money(34, 5), Money(12, 0))
def totalAllExpenses(expenses: List[Money])(implicit m: Monoid[Money]): Money = {
expenses.foldLeft(m.empty){
case (acc, money) => m.combine(acc, money)
}
}
println(s"LastYearExpenses : ${totalAllExpenses(lastYearExpenses)}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment