The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

327011 (7) [Avatar] Offline
#1
Hi,
The code is in Monoid.Scala... trying to figure out how the implicit resolution happens:
The client code is

  implicit def BalanceAdditionMonoid = new Monoid[Balance] {
    val m = implicitly[Monoid[Money]] // I extracted a temp variable m 
    def zero = Balance(zeroMoney)
    def op(b1: Balance, b2: Balance) = Balance(m.op(b1.amount, b2.amount))
  }


There are two possible implicits in scope...

1.
  implicit def MoneyAdditionMonoid = new Monoid[Money] {
    val m = implicitly[Monoid[Map[Currency, BigDecimal]]] // comment this line, the ambiguous resolution error results
    def zero = zeroMoney
    def op(m1: Money, m2: Money) = Money(m.op(m1.m, m2.m))
  }


versus

2.
 implicit val MoneyCompareMonoid = new Monoid[Money] {
    def zero = zeroMoney
    def op(m1: Money, m2: Money) = if (gt(m1, m2)) m1 else m2
  } 


The MoneyAdditionMonoid is correctly picked up... not sure how/why the MoneyAdditionMonoid takes precedence over MoneyCompareMonoid?

Any pointers? I searched - and played with the code

 implicit def MoneyAdditionMonoid = new Monoid[Money] {
    val m = implicitly[Monoid[Map[Currency, BigDecimal]]] 
...


Somehow the above val m = implicitly... line helps resolve it - not sure how -
any pointers/reading hints? Would love to understand this smilie