Skip to content

Commit

Permalink
Add Semigroup.instance method
Browse files Browse the repository at this point in the history
  • Loading branch information
jozic committed Dec 13, 2017
1 parent e27266a commit f126e29
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
9 changes: 8 additions & 1 deletion kernel/src/main/scala/cats/kernel/Semigroup.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cats.kernel

import scala.{ specialized => sp }
import scala.annotation.{ tailrec }
import scala.annotation.tailrec

/**
* A semigroup is any set `A` with an associative operation (`combine`).
Expand Down Expand Up @@ -76,4 +76,11 @@ object Semigroup extends SemigroupFunctions[Semigroup] {
* Access an implicit `Semigroup[A]`.
*/
@inline final def apply[A](implicit ev: Semigroup[A]): Semigroup[A] = ev

/**
* Create a `Semigroup` instance from the given function.
*/
@inline def instance[A](cmb: (A, A) => A): Semigroup[A] = new Semigroup[A] {
override def combine(x: A, y: A): A = cmb(x, y)
}
}
14 changes: 12 additions & 2 deletions tests/src/test/scala/cats/tests/SemigroupSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package cats
package tests

import org.scalatest._
import org.scalatest.prop.GeneratorDrivenPropertyChecks



class SemigroupSuite extends FunSuite {
class SemigroupSuite extends FunSuite with Matchers with GeneratorDrivenPropertyChecks {
{
import cats.implicits._
Invariant[Semigroup]
Expand All @@ -19,4 +19,14 @@ class SemigroupSuite extends FunSuite {
Semigroupal[Semigroup]
InvariantMonoidal[Semigroup]
}

test("Semigroup.instance creates a Semigroup from the given function") {
val mult: (Int, Int) => Int = (a, b) => a * b
val add: (Int, Int) => Int = (a, b) => a + b

forAll { (a: Int, b: Int) =>
Semigroup.instance(mult).combine(a, b) should === (a * b)
Semigroup.instance(add).combine(a, b) should === (a + b)
}
}
}

0 comments on commit f126e29

Please sign in to comment.