简体   繁体   中英

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

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?

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.

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