//arrow-core/arrow.typeclasses/Semiring
The Semiring type class for a given type A
combines both a commutative additive Monoid and a multiplicative Monoid. It requires the multiplicative Monoid to distribute over the additive one. The operations of the multiplicative Monoid have been renamed to one and combineMultiplicate for easier use.
The one function serves exactly like the empty function for an additive Monoid, just adapted for the multiplicative version. This forms the following law:
Please note that the empty function has been renamed to zero to get a consistent naming style inside the semiring.
Currently, Semiring instances are defined for all available number types.
Here a some examples:
import arrow.typeclasses.Semiring
fun main(args: Array<String>) {
val result =
//sampleStart
Semiring.int().run { 1.combine(2) }
//sampleEnd
println(result)
}
import arrow.typeclasses.Semiring
fun main(args: Array<String>) {
val result =
//sampleStart
Semiring.int().run { 2.combineMultiplicate(3) }
//sampleEnd
println(result)
}
The type class Semiring
also has support for the +
*
syntax:
import arrow.typeclasses.Semiring
fun main(args: Array<String>) {
val result =
//sampleStart
Semiring.int().run {
1 + 2
}
//sampleEnd
println(result)
}
import arrow.typeclasses.Semiring
fun main(args: Array<String>) {
val result =
//sampleStart
Semiring.int().run {
2 * 3
}
//sampleEnd
println(result)
}
Name | Summary |
---|---|
Companion | common object Companion |
Name | Summary |
---|---|
combine | common abstract fun A.combine(b: A): A |
combineMultiplicate | common abstract fun A.combineMultiplicate(b: A): A Multiplicatively combine two A values. |
maybeCombineAddition | common open fun A?.maybeCombineAddition(b: A?): A Maybe additively combine two A values. |
maybeCombineMultiplicate | common open fun A?.maybeCombineMultiplicate(b: A?): A Maybe multiplicatively combine two A values. |
one | common abstract fun one(): A A one value for this A |
plus | common open operator fun A.plus(b: A): A |
times | common open operator fun A.times(b: A): A |
zero | common abstract fun zero(): A A zero value for this A |
Do you like Arrow?
✖