Documentation

Lean.Elab.ComputedFields

Computed fields #

Inductives can have computed fields which are recursive functions whose value is stored in the constructors, and can be accessed in constant time.

inductive Exp
  | hole
  | app (x y : Exp)
with
  f : Exp → Nat
    | .hole => 42
    | .app x y => f x + f y

-- `Exp.f x` runs in constant time, even if `x` is a dag-like value

This file implements the computed fields feature by simulating it via implemented_by. The main function is setComputedFields.

Marks a function as a computed field of an inductive.

Computed fields are specified in the with-block of an inductive type declaration. They can be used to allow certain values to be computed only once at the time of construction and then later be accessed immediately.

Example:

inductive NatList where
  | nil
  | cons : Nat → NatList → NatList
with
  @[computed_field] sum : NatList → Nat
  | .nil => 0
  | .cons x l => x + l.sum
  @[computed_field] length : NatList → Nat
  | .nil => 0
  | .cons _ l => l.length + 1
Equations
    Instances For
      Equations
        Instances For
          @[reducible, inline]
          Equations
            Instances For
              Equations
                Instances For
                  Equations
                    Instances For

                      Sets the computed fields for a block of mutual inductives, adding the implementation via implemented_by.

                      The computedFields argument contains a pair for every inductive in the mutual block, consisting of the name of the inductive and the names of the associated computed fields.

                      Equations
                        Instances For