I am trying to write a function that converts integers to natural numbers in OCaml. Here is my code
type nat = Zero | Succ of nat
let rec int_to_nat (x:int):nat option=
if x<0 then
None
else if x=0 then
Some Zero
else
Succ(int_to_nat (x-1));;
The compiler prompts "This variant expression is expected to have type nat option.The constructor Succ does not belong to type option" error. I don't understand what does it mean.
Succ(...)
has typenat
, but ti expects anat option
, likeSome (Succ ...)
, because that's what the other two branches of theif
expression returns. They all need to return the same type, otherwise what would the type of the entireif
expression be? – glennsl