← back to index

Algebras for Weighted Search

Donnacha OisΓ­n Kidney & Nicolas Wu Β· ICFP 2021 Β· ACM

Prereqs: 🍞 Fritz 2020 (Kleisli composition). Familiarity with monads helps.

Weighted search is parameterized by a wpsemiring. Choose the semiring and you choose the semantics: natural numbers for counting, reals in [0,1] for probability, booleans for reachability. One monad, many interpretations.

Probability S = [0,1] ⊕ = +, ⊗ = × weights sum to 1 Counting S = N ⊕ = +, ⊗ = × a ×3 b ×1 c ×2 weights count paths Search S = Bool ⊕ = ∨, ⊗ = ∧ reachable reachable unreachable weights are true/false same monad, different semiring, different meaning

The free semimodule monad

A weighted collection assigns a weight from a semiring S to each element. When S = β„•, you're counting occurrences. When S = [0,1] with ordinary multiplication, you're assigning probabilities. The free semimodule monad over S captures all of these at once.

Semiring Values Zero One Plus Times Meaning
Probability[0,1]01+×how likely
Counting01+×how many ways
SearchBoolfalsetrueorandis it reachable
Scheme
Python

Bind over different semirings

Monadic bind (>>=) for weighted search: for each element, apply the function and multiply weights. The semiring's multiplication combines the weights. Its addition collects duplicates.

Scheme
Python

Semiring = β„• gives counting

When S = β„• (natural numbers with +, Γ—), weights count multiplicity. Bind sums the number of paths reaching each state. This is nondeterministic search with counting.

Scheme
Python

Semiring = [0,1] gives probability

When S = [0,1] with ordinary multiplication and addition (capped at 1 for subdistributions), weights are probabilities. Bind marginalizes over intermediate states. This recovers 🐱 Kleisli composition from 🍞 Fritz 2020.

Scheme
Python

Notation reference

Paper Scheme Meaning
S; semiring (β„•, [0,1], Bool)Weight semiring
S⟨X⟩'((val . weight) ...)Free semimodule (weighted bag)
>>=(weighted-bind bag f ...)Monadic bind (multiply then collect)
Ξ·(x)(list (cons x 1))Return (singleton with unit weight)
βŠ•, βŠ—+, *Semiring addition and multiplication
Neighbors

Other paper pages

Foundations (Wikipedia)

Translation notes

The examples use association lists with explicit semiring operations. Kidney and Wu work with free semimodule monads in Haskell, using type classes to abstract over the semiring. For example: the counting example above uses an explicit loop with set-cdr! to merge duplicates. In the paper, this is the free semimodule's universal property β€” the unique algebra morphism that folds a formal sum into a concrete semiring value. The computation is the same; the universality guarantee is not.

Every example is Simplified.

Ready for the real thing? Read the paper (ICFP 2021). Start at Β§3 for the free semimodule monad, Β§5 for the semiring-parameterized search.