Recursive functions #
We have defined functions in terms of other functions. Besides this essentially the only way to define functions is recursion. In Dependent Type Theory recursion/induction is very powerful.
In particular, unlike imperative programming all loops are implemented in terms of recursion.
The first example is the factorial function:
We check by evaluating this
#eval fctrl 5 -- 120
Fibonacci numbers: #
These are given by the recursive definition
The above definition is not efficient as a single computation is called many times.
To define Fibonacci pairs as above, we have two choices. We can view the pair at
n as obtained by
n iterations of the function
g: (a, b) ↦ (b, a + b) starting with the pair
(1,1). Note that we can recursively use either
g^(n + 1) = g^n ∘ g or
g^(n + 1) = g ∘ g^n. The former is more efficient as it means the recursive function is called at the end to give a result, with modified arguments. This allows so called tail call optimization, where new copies of the function are not created.
The following definition is clearly wrong and will loop infinitely. Indeed if we attempt to define
we get the error message
However even if functions terminate we can still get such an error. This is because Lean does not know that the function is terminating. We can fix this by adding the
partial keyword but better still we can prove termination.
Thus, the following definition is correct but gives an error.
partial def wrong(n: ℕ): Empty := wrong (n + 1)
gives the error message
failed to compile partial definition 'wrong', failed to show that type is inhabited and non empty
Lean has to allow partial definitions due to deep results of Church-Gödel-Turing-..., which say for example that we cannot prove that a Lean interpreter in Lean terminates.