Rob
Rob

Reputation: 3459

Require semigroup to be associative in scala

A semigroup is required to be associative, but I could define a Semigroup like:

trait Semigroup[T] {
  def op(t1:T, t2:T) : T
}

def plus = new Semigroup[Int] { def op(t1:Int, t2:Int) = t1 - t2 }

I am able to implement plus which is not associative, yet the class is still a Semigroup. Is there a safeguard in place against this or is the user expected to rely on testing to prevent this?

Upvotes: 0

Views: 206

Answers (1)

Andronicus
Andronicus

Reputation: 26046

There will be no compilation exception, that the associativity property does not hold. In other words, it's up to you to make sure it's implemented correctly.

But if you use cats, you can use laws to make sure all the properties required for the semigroup and other structures defined in cats. Take a look at the documentation. You can create a test to check if the semigroup you defined is alright:

class TreeLawTests extends AnyFunSuite with Discipline {
  checkAll("YourSemigroup[YourType].SemigroupLaws", SemigroupTests[YourSemigroup[YourType]].semigroup)
}

Upvotes: 4

Related Questions