(* Define a function sum_digits such that its input is an int, the base of which is b and its
output is the sum of all its digits *)
Definition sum_digits (digits : nat) (base : nat) : nat :=
let fix aux (sum : nat) (x_value : nat) : nat :=
if leb x_value 0 then
sum
else
aux (add sum (modulo x_value base)) (div x_value base) in
aux 0 digits.
Error: Cannot guess decreasing argument of fix.
I Defined a function according to the description above, but it seems that Coq cannot deal with this kinds of recursion. How could I fix this problem?
You can use the
Program
library. It can sometimes be a little tricky to use, but in this case it works fine. You enter your program, and then you get a bunch of obligations to solve.Next Obligation.
gives you the next obligation to solve.Here we say
{measure digits}
which means thatdigits
will be strictly decreasing. This will guarantee that the execution eventually terminates.Note that I write
dec (eqb digits 0)
so that we don't forget thatdigits != 0
in the second branch.When we do
Next Obligation.
we get the goalLet's search for a proof of this.
Ouch. This is something that we can't prove unless we also know that
1 < base
. Let's add an argumentHbase: 1<base
.Change that, and apply
div_lt.
Finally use(digits =? 0) = false
to prove that0 < digits
. Search for something that can help us.Lets apply that. And we're essentially done.
Here is the complete session.
Try it with
ADDENDUM:
When you build terms with
Program
you end up with a godawful term that is very annoying to reason with. Therefore you need a lemma about your proof term that you can use to rewrite with.It is usually very hard to see what needs to be done when you are proving this lemma, but usuall you mostly have to do case splits to split the match statements into finer details.
Here is an example of the lemma that you would need for this function. It may be useful to look at the proof if you need to do use
Program
with some other function.With this function it is easier to prove other properties about the function, i.e.