0

Why does Semigroup has an Option type and None behave like a neutral element in Monoid?

val two: Option[Int] = Option(2)
val n: Option[Int] = None

n |+| two should be(Some(2))//why do we have the opportunity to do this?
two |+| n should be(Some(2))//n look like neutral here

Semigroup[Option[Int]].combine(Option(1), None) should be(Some(1))//why does semigroup has it?
  • Not sure what your question is. – Luis Miguel Mejía Suárez Sep 02 '20 at 19:26
  • monoid by definition is a semigroup with the neutral element, but in this case - Option type, we see that None( Option type projection) do like an neutral element in monoid. But why semigroup can deal with it at all? – Остап Страшевский Sep 02 '20 at 19:33
  • 3
    Every monoid is by definition a semigroup. Not surprising that a monoid supports `|+|` operation of Semigroup. – simpadjo Sep 02 '20 at 19:39
  • 1
    The **Semigroup** of **Option** is the **Monoid** of **Option** _(since the ability to define the most concrete one imply the most abstract one)_, so that should answer your question. - Additionally, what would you expect the result to be in any case? For a valid **Semigroup** definition, its `combine` must be able to accept any two arbitrary values of the corresponding type and return another value that is also part of the corresponding type, so `Option(2) |+| None` has to return a valid **Option**, which one would it be? - Finally, this is true for all other types, ask for `1 + 0` – Luis Miguel Mejía Suárez Sep 02 '20 at 19:40
  • Ok, thanks, from this point of view("since the ability to define the most concrete one imply the most abstract one") it would be easier to understand all other categories. I looked at them in more "separate" way... but found that... trait Monoid[@sp(Int, Long, Float, Double) A] extends Any with Semigroup[A] – Остап Страшевский Sep 02 '20 at 20:02
  • 1
    You may be interested in this: https://github.com/tpolecat/cats-infographic/blob/master/cats.svg – Luis Miguel Mejía Suárez Sep 02 '20 at 20:10

1 Answers1

2

Every Monoid is also a Semigroup. Semigroup doesn't have to have an identity element, but every Semigroup that is also a Monoid will always have one (without "knowing" about the concept).

Another example: "addition of integers" semigroup doesn't formally posses an identity element (zero). It doesn't define one. But you can still add 3 + 0 = 3.

slouc
  • 9,508
  • 3
  • 16
  • 41