I am currently reading the first volume of the softwarefoundations series. In one of the exercises I am supposed to write a function which turns a natural number (unary form) into the equivalent binary number.
This is my code/approach:
Inductive bin : Type :=
| Z
| B0 (n : bin)
| B1 (n : bin).
Fixpoint evenb (n:nat) : bool :=
match n with
| O => true
| S O => false
| S (S n') => evenb n'
end.
Fixpoint nat_to_bin (n:nat) : bin :=
match n with
| 0 => Z
| 1 => B1 Z
| 2 => B0 (B1 Z)
| m => match evenb(m) with
| true => B0 (nat_to_bin (Nat.div m 2))
| false => B1 (nat_to_bin (Nat.modulo m 2))
end
end.
I am using https://jscoq.github.io/scratchpad.html to work on these exercises. Now I get this error message:
Recursive definition of nat_to_bin is ill-formed. In environment nat_to_bin : nat -> bin
n : nat
n0 : nat
n1 : nat
n2 : nat
Recursive call to nat_to_bin has principal argument equal to "Nat.div n 2 " instead of one of the following variables: "n0" "n1" "n2" . Recursive definition is: "fun n : nat => match n with
| 0 => Z
| 1 => B1 Z
| 2 => B0 (B1 Z )
| S (S (S _) ) =>
if evenb n then B0 (nat_to_bin (Nat.div n 2 ) )
else B1 (nat_to_bin (Nat.modulo n 2 ) )
end " .