Documentation

PfsProgs25.Unit08.RecFunction

Recursion and Induction on (Indexed) Inductive Types #

We have been using match expressions to define functions on inductive types. In this file, we will see how to define functions using recursion and induction principles. These principles are automatically generated by Lean when an inductive type is defined, with functions like Nat.rec automatically introduced.

The function that allows us to define (dependent) functions by recursion and prove results by induction on the natural numbers is Nat.rec. It has the following type:

The motive should really be motif, i.e., a template. To define functions to say Nat, the motive is the constant function with value Nat. We will first focus on this case. The motive is constant for recursive definitions of (non dependent) functions.

What the above says is that to define a function f recusively, the data we need is:

  1. The value of f at 0.
  2. The function f at n + 1 given n and the value f n of f at n.
def fctrl :
Equations
Instances For
    def fctrl' :
    Equations
    Instances For
      def stringFromNat (t : ) :
      (fun (x : ) => String) t
      Equations
      Instances For
        def even :
        Bool
        Equations
        Instances For

          When a function f is defined using Nat.rec, some definitional equalities are automatically generated. For example, the following is true by definition:

          theorem fctrl_zero :
          fctrl 0 = 1
          theorem fctrl_succ (n : ) :
          fctrl (n + 1) = (n + 1) * fctrl n

          We can write the definitional equalities in a general form.

          theorem Nat.recFn_zero {α : Type u} (zeroData : α) (stepData : αα) :
          Nat.rec zeroData stepData 0 = zeroData
          theorem Nat.recFn_succ {α : Type u} (zeroData : α) (stepData : αα) (n : ) :
          Nat.rec zeroData stepData (n + 1) = stepData n (Nat.rec zeroData stepData n)

          We see next recursive definitions of dependent functions. The motive is not constant in this case.

          Concretely, we define:

          def Tuple :
          Type
          Equations
          Instances For

            Note that × and are right-associative. So, ℕ × ℕ × Unit is the same as ℕ × (ℕ × Unit).

            def tuple (n : ) :
            Tuple (n + 1)
            Equations
            Instances For
              def tuple' (n : ) :
              Tuple (n + 1)
              Equations
              Instances For

                The recursive definition of tuple' satisfies the following definitional equalities.

                theorem tuple'_zero :
                tuple' 0 = (0, ())
                theorem tuple'_succ (n : ) :
                tuple' (n + 1) = (n + 1, tuple' n)