arrow-core / arrow.typeclasses / Semiring

Semiring

interface Semiring<A>

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.

(a.combineMultiplicate(b)).combineMultiplicate(c) == a.combineMultiplicate(b.combineMultiplicate(c))

The one function serves exactly like the empty function for an additive Monoid, just adapted for the multiplicative version. This forms the following law:

a.combineMultiplicate(one()) == one().combineMultiplicate(a) == a

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.

Examples

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)
}

Functions

combine abstract fun A.combine(b: A): A
combineMultiplicate Multiplicatively combine two A values.abstract fun A.combineMultiplicate(b: A): A
maybeCombineAddition Maybe additively combine two A values.open fun A?.maybeCombineAddition(b: A?): A
maybeCombineMultiplicate Maybe multiplicatively combine two A values.open fun A?.maybeCombineMultiplicate(b: A?): A
one A one value for this Aabstract fun one(): A
plus open operator fun A.plus(b: A): A
times open operator fun A.times(b: A): A
zero A zero value for this Aabstract fun zero(): A

Companion Object Functions

byte fun byte(): Semiring<Byte>
double fun double(): Semiring<Double>
float fun float(): Semiring<Float>
int fun int(): Semiring<Int>
long fun long(): Semiring<Long>
short fun short(): Semiring<Short>

Do you like Arrow?

Arrow Org
<