Recursion and Induction
By Eunice Chen, June 2020
Types
For each of the following expressions, state its type and value.
fun f (x : int) : int = f x
val x = [122]::([150]::[])
fun f L =
case L of
[] => [[]]
| x::xs => [x + 1] @ []
What is the type and value of x?
fun f (y : int) : int = f y
val x : int = f y
What is the type and value of y?
val x =
let
fun incr (n : int) = n + 1
in
incr
end
val y = incr
Induction
Given the following function:
fun length [] = 0
| length (x::xs) = 1 + length(xs)
fun append ([], L) = L
| append (x::xs, L) = x :: append(xs, L)
Prove that for all L1,L2:int list,
length(append(L1,L2))=length(L1)+length(L2) Proof: By structural induction on L1.
Base case
Base case (BC): L1=[]
Proof, from left-hand side (LHS):
== length(append(L1,L2)) length(append([],L2)) length(L2)Clause 1 of append From right-hand-side (RHS):
=== length(L1)+length(L2) length([])+length(L2) 0+length(L2) length(L2)Clause 1 of lengthmath and totality of length LHS and RHS are both equivalent to identical expressions, and are thus equivalent by transitivity.
Inductive case
Inductive step (IS): L1=x::xs for some x:int, xs:int list
Inductive hypothesis (IH):
length(append(xs,L2))=length(xs)+length(L2)
Want to show (WTS):
length(append(x::xs,L2))=length(x::xs)+length(L2)
Proof, from LHS:
==== length(append(L1,L2)) length(append(x::xs,L2) length(x::append(xs,L2)) 1+length(append(xs,L2)) 1+length(xs)+length(L2)Clause 2 of appendClause 2 of length, totality of appendIH From RHS:
== length(L1)+length(L2) length(x::xs)+length(L2) 1+length(xs)+length(L2)Clause 2 of length QED.