Continuing my series of questions regarding type-level arithmetic, I stumbled across another problem: return types of polymorphic recursive functions.
This is the code:
module Nat : sig
type z = Z
type 'n s = S of 'n
type ('n) nat =
Zero : (z) nat
| Succ : ('n) nat -> ('n s) nat
val of_int : int -> 'n nat
end = struct
type z = Z
type 'n s = S of 'n
type ( 'n) nat =
Zero : ( z) nat
| Succ : ('n) nat -> ('n s) nat
let rec of_int n : int -> 'n nat = function
0 -> Zero
| n -> Succ (of_int (n - 1))
end
Compiling yields:
Error: This expression [Succ (of_int (n - 1))] has type 'a s nat
but an expression was expected of type z nat
The problem is that the return value of the function is set to z nat by Zero in the first pattern matching clause. Instead it should be something like 'a. 'a nat? This problem also occurs when trying to make a function that adds two different Nat:s.
Grateful for your help.