← back to lean navigator

Hoare/Graded.lean

ghView source on GitHub

Extends Hoare triples with a cost bound (grade) drawn from a preordered monoid — a behavioral guarantee plus a quantitative information budget.

PreorderedMonoid

A typeclass for grade structures: a carrier type G with addition, zero, a preorder, and a toNat extraction. The key laws: addition is associative with unit, the preorder respects addition, and toNat is both order-preserving and additive. The canonical instance is Nat itself.

class PreorderedMonoid (G : Type) where
  add : G → G → G
  zero : G
  le : G → G → Prop
  toNat : G → Nat
  -- ... associativity, unit laws, monotonicity, toNat laws

GradedTriple

A graded Hoare triple {P} f {Q} @ g combines a behavioral guarantee (every reachable output satisfies Q) with a cost bound (the information drop is bounded by toNat g). The cost is stated additively to avoid natural number subtraction.

def GradedTriple [Monad M] [Support M] {G : Type} [PreorderedMonoid G]
    (P : α → Prop) (f : Kernel M α β) (Q : β → Prop)
    (mα : InfoMeasure α) (mβ : InfoMeasure β) (g : G) : Prop :=
  Triple P f Q ∧
  ∀ a, P a → ∀ b, Support.support (f a) b →
    mα.measure a ≤ mβ.measure b + PreorderedMonoid.toNat g
Python

graded_contract_bridge

One direction of the bridge: ContractPreserving plus a supplied cost bound gives a GradedTriple. The grade is whatever the caller provides.

graded_comp

Graded triples compose with additive grades. If {P} f {R} @ g1 and {R} g {Q} @ g2, then {P} f;g {Q} @ (g1 + g2). The cost chain uses toNat_add to convert the composed grade into the sum of costs.

graded_skip

The identity kernel has unit grade: {P} id {P} @ zero. Since the only output is the input itself, the information drop is zero.

graded_weaken

Weakening: a graded triple at grade g1 implies a graded triple at any larger grade g2. Larger grade means a looser cost bound, which is easier to satisfy. Uses toNat_mono for the numeric comparison.

Connections

Neighbors