简体   繁体   中英

Implementing Monoid[Option[A]] Compile-time Error

When trying to implement the optionMonoid[A] from FP in Scala , I wrote:

def optionMonoid[A] = new Monoid[Option[A]] {
    def op(a1: Option[A], a2: Option[A]) = (a1, a2) match {
        case (Some(x), Some(y)) => Some(x + y)
        case _ => None
    }
    val zero = None
}

Why is the compile-time error expecting a String here?

C:\Users\Kevin\Workspace\side-work\Monoid>scalac MonoidTesting.scala
MonoidTesting.scala:43: error: type mismatch;
 found   : A
 required: String
                        case (Some(x), Some(y)) => Some(x + y)
                                                        ^

I'm guessing you need to pass a Monoid instance for A so you can op the two values in the Some(x), Some(y) case. From memory, this is usually done with an implicit arg:

def optionMonoid[A](implicit aMonoid:Monoid[A]) = ...

    case (Some(x),Some(y)) => Some(aMonoid.op(x,y))

You'll need to fix your zero definition too, as it currently won't satisfy the Monoid identity law, ie, op(x, zero) === x === op(zero, x) . I think this is a useful exercise to work out, so I'll omit the implementation for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM