简体   繁体   中英

Difference between Semigroup and SemigroupK

In cats there are 2 semigroup types classes: Semigroup and SemigroupK with the latter working on type constructors. I fail to see the advantages of the latter over the former. If I look at the list instances they are providing Monoid (although there is a MonoidK ), whereas NonEmptyList is providing a SemigroupK . Note that NonEmptyList is also providing a Semigroup via the following method:

implicit def catsDataSemigroupForNonEmptyList[A]: Semigroup[NonEmptyList[A]] =
  SemigroupK[NonEmptyList].algebra[A]

Why the discrepancy?

Then it seems that most semigroup operations are only available on Semigroup and not SemigroupK (there's reduceK in Reducible but that's the only one I saw, and it delegates to reduce which works on Semigroup ).

So, given a type T[_] , what would you gain by having both a SemigroupK[T] and a Semigroup[T[A]] for some A ?

Edit

There's now an issue to remove MonoidK and SemigroupK: https://github.com/typelevel/cats/issues/1932

One thing you can do with SemigroupK which you can't do with Semigroup is to compose instances for Nested :

implicit def catsDataSemigroupKForNested[F[_]: SemigroupK, G[_]]: SemigroupK[Nested[F, G, ?]]

If you try to write an equivalent for Semigroup , I think the closest you would get is

implicit def catsDataSemigroupForNested[F[_], G[_], A](implicit sg: Semigroup[F[G[A]]]): Semigroup[F[G[A]]] // or Semigroup[Nested[F, G, A]]

which is not very useful! From search, I can't see anything else which is implemented for SemigroupK and can't be done using Semigroup , but I might have missed something.

But the main point of SemigroupK is that once you have it, you can automatically get a Semigroup too, exactly like NonEmptyList does.

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