Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Semigroup.instance method #2101

Merged
merged 1 commit into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
}