1

In the cats docs they show an example for Semigroup[Int]:

val list = List(1, 2, 3, 4, 5) val rightwards = List(1, 2, 3).foldRight(0)(_ |+| _) 

So the |+| operator is a semigroup combine. What's the point of this extra machinery if good 'ol "+" works just fine here? What does the Semigroup buy you for Int, or likely for any simple type for that matter?

5
  • 2
    Semigroup is an abstraction, Int + is an implementation. Abstractions (FP type classes or OOP interfaces/traits) are good for decoupling. Commented Oct 10, 2022 at 1:14
  • 3
    The point of an abstraction is usually using it on an abstract context, is like asking what is the point of Animal if I all I want is a Dog - BTW, in this case you can actually see advantages without needing to go abstract, just use combineAll rather than foldRight or use |+| with two maps whose values are Ints Commented Oct 10, 2022 at 1:16
  • 1
    In addition to the above comments, basically these are all building blocks of a bigger building, so your question can be expanded to: "What's the point of a Semigroup, Monoid, and so on?", and the answer would be clear. Commented Oct 10, 2022 at 10:04
  • stackoverflow.com/questions/62103426/… Commented Nov 2, 2022 at 15:45
  • I like the point with Animal and Dog and to fine grain + is the "operation" on them which could be "kill" or "love" each other. Cats provides the implementation for primitive data types. If have a case class let's say case class SalesCustomer( count:Int, value:Int) you can then create a semigroup to add up the number of all sales and revenue without having to implement the operation of Semigroup(Int,+) in first place. Commented Apr 18, 2023 at 8:16

1 Answer 1

0

Semigroup is an abstraction. The point of it is that you can abstract things.

Instead of

def combineIntList(xs: List[Int]) = xs.foldRight(0)(_ + _) def combineDoubleList(xs: List[Double]) = xs.foldRight(0d)(_ + _) def combineStringList(xs: List[String]) = xs.foldRight("")(_ + _) 

You write

def combine[A: Monoid](xs: List[A]) = xs.foldRight(Monoid[A].empty)(_ |+| _) 

The free (pay what you want) ebook Scala with Cats talks about these concepts in much more detail

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.