Semiring

While a group, monoid, and semigroup are defined by a set and a single operation, a semiring is defined by a set and two operations. Given a set R and operations + and *, we say that (R, +, *) is a semiring if it satisfies the following properties:

The laws of a commutative monoid under addition must hold for a semiring:

and the laws of a semigroup under multiplication:

as well as distributivity and the multiplicative zero property:

Code

trait MultiplicativeSemigroup[A]:
  def times(x: A, y: A): A

trait Semiring[A] extends CMonoid[A], MultiplicativeSemigroup[A]    

Laws

Exercises

Exercise 1.5.1: Implementing a Semiring for Integers.

Exercises repository with instructions

Fill in the missing parts (???):

given Semiring[Int] with
  val empty: Int = ???
  
  def combine(x: Int, y: Int): Int = 
    ???
    
  def times(x: Int, y: Int): Int = 
    ???

🔍 Show Solution

given Semiring[Int] with
  val empty: Int = 0
  
  def combine(x: Int, y: Int): Int = 
    x + y
    
  def times(x: Int, y: Int): Int = 
    x * y 

Example calls:

Semiring[Int].combine(5, 3)
// 8
Semiring[Int].empty
// 0
Semiring[Int].times(5, 3)
// 15

Diagram

classDiagram
    class Semigroup~A~{
        +combine(x: A, y: A) A
    }
    class Monoid~A~{
        +empty() A
    }
    Semigroup <|-- Monoid
    class CommutativeSemigroup~A~
    Semigroup <|-- CommutativeSemigroup  
    class CommutativeMonoid~A~
    Monoid <|-- CommutativeMonoid
    CommutativeSemigroup <|-- CommutativeMonoid
    class Semiring~A~
    CommutativeMonoid <|-- Semiring
    class MultiplicativeSemigroup~A~{
        +times(x: A, y: A) A
    }
    MultiplicativeSemigroup <|-- Semiring
    Semigroup .. MultiplicativeSemigroup

Library Implementations

Implementation in Spire

Semiring[A] provides +, zero, and *. Semiring[A] extends AdditiveCommutativeMonoid[A] and MultiplicativeSemigroup[A].

import spire.algebra.Semiring
import spire.math.Rational

Semiring.plus(Rational(1, 2), Rational(1, 3))
// val res0: spire.math.Rational = 5/6
Semiring.times(Rational(1, 2), Rational(1, 3))
// val res1: spire.math.Rational = 1/6
Semiring.pow(Rational(1, 2), 3)
// val res2: spire.math.Rational = 1/8

References: