Write a function (int_to_whole) in OCaml that converts an integer into a whole number if one exists (a whole number is 1, 2, 3, ...). Use an option type because not all integer inputs can be converted.
type whole = One | Succ of whole;;
let int_to_whole (x:int) : whole option = ...
type whole = One | Succ of whole;;
let rec int_to_whole (x:int) : (whole option) =
if x < 0 then None else
match x with
| 0 -> None
| _ -> let y = int_to_whole (x+1) in
match y with
| None -> None
| Some z -> Some (Succ z);;
However, this will lead to stack overflow for large x. You can resolve this problem by making it tail-recursive:
type whole = Zero | Succ of whole
let int_to_whole (x:int) : (whole option) =
if x < 0 then None else
let rec int_to_whole' (x:int) (accum:whole) : (whole option)
=
match x with
| 0 -> Some accum
| _ -> int_to_whole' (x+1) (Succ accum)
in int_to_whole' x Zero;;
This OCaml code are correct .
So please any queries please tell here .
Thank you.
Get Answers For Free
Most questions answered within 1 hours.