How do I declare a scala case class to be an instance of Scalaz's Semigroup?

257 views Asked by At

I have a type, defined as follows:

import scalaz._, Scalaz._
case class MyInt(i : Int)

I want to make an instance of Semigroup. I tried this:

object MyInt {
  implicit def myIntSemigroup: Semigroup[MyInt] = new Semigroup[MyInt] {                                                                                                                                                                       
    def append(a: MyInt, b: MyInt) : MyInt = MyInt(a.i + b.i)
  }
}

When I run sbt console, I get this error:

[info] Set current project to hello (in build file:/home/mp/code/scala/examples/semigroup/)
[info] Compiling 1 Scala source to /home/mp/code/scala/examples/semigroup/target/scala-2.10/classes...
[error] /home/mp/code/scala/examples/semigroup/src/main/scala/Main.scala:6: object creation impossible, since method append in trait Semigroup of type (f1: MyInt, f2: => MyInt)MyInt is not defined
[error]   implicit def myIntSemigroup: Semigroup[MyInt] = new Semigroup[MyInt] {                                                                                                                                                               
[error]                                                       ^   
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 5 s, completed 25-Jun-2015 08:15:37

How do I make MyInt a Semigroup so I can use |+| on it?

For completeness, here is my build.sbt file:

name := "hello"
version := "1.0"
scalaVersion := "2.10.5"
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.1.3"
1

There are 1 answers

0
Edmondo On BEST ANSWER

If you look carefully for the signature of the Scalaz semigroup, the second parameter is defined as by name while in your implementation you are having a different signature. Change your second parameter to b: => MyInt and it should compile