I'm trying to learn exactly what it means to prove a program correct. I'm starting from scratch and getting hung up on the first steps/the introduction to the topic.
In this paper on total functional programming, two definitions of the fibonacci function are given. The traditional one:
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
--fib (n+2) = fib (n+1) + fib (n+2) --The definition as given in the paper
--It seems incorrect to me. Typo?
and a tail recursive version I had never seen before:
fib' n = f n 0 1
f 0 a b = a
f n a b = f (n-1) b (a+b)
The paper then claimed that it is "straightforward" to prove by induction that both functions return the same result for all positive Integers n. This is the first time I've thought of analysing programs like this. It's quite interesting to think that you can prove that two programs are equivilent, so I immediately tried to do this proof by induction myself. Either my maths skills are rusty or the task is not actually all that straightforward.
I proved for n = 1
fib' 1 = f 1 0 1
= f 0 1 1
= 1
fib 1 = 1 (By definition)
therefore
fib' n = fib n for n = 1
I made the n = k assumption
fib' k = fib k
f k 0 1 = fib k
I start trying to prove that if the assumption holds true, then the functions are also equivilant for n = k + 1 (and hence they are all equivalent for all n >= 1 QED)
fib' (k+1) = fib (k+1)
f (k+1) 0 1 = fib k + fib (k-1)
I've tried various manipulations, substituting the assumption in at the right time and so on, but I just can't get LHS to equal RHS and therefore prove that the functions/programs are equivalent. What am I missing? The paper mentions that the task is equivalent to proving
f n (fib p) (fib (p+1)) = fib (p+n)
by induction for arbitrary p. But I don't see how that's true at all. How did the authors arrive at this equation? That's a valid transformation on the equation only if p = 0
. I don't see how that means it works for arbitrary p. To prove it for arbitrary p requires you to go through another layer of induction. Surely the correct formula to prove would be
fib' (n+p) = fib (n+p)
f (n+p) 0 1 = fib (n+p)
So far that hasn't helped either. Can anyone show me how the induction would be done? Or link to a page that shows the proof (I did search, couldn't find anything).
fib (n+2) = fib (n+1) + fib (n+2)
is clearly a typo, they probably meantfib (n+2) = fib (n+1) + fib n
which is mathematically correct, but is getting removed from valid Haskell hackage.haskell.org/trac/haskell-prime/wiki/RemoveNPlusK – Materi