With my original code I kept getting Error: Parse error: [expr level ;] expected after "in" (in [expr])
on the line let numDigits = numDigits - 1 in
Original:
let rec rev_int num = if num / 10 == 0 then num else let temp = num mod 10 in let numDigits = String.length(string_of_int num) - 1 in if num < 0 then let numDigits = numDigits - 1 in else let numDigits = numDigits + 0 in let num = (num - temp) / 10 in temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num
With variations of:
if num < 0 then let numDigits = numDigits - 1 in; else let numDigits = numDigits + 0 in;
if num < 0 then let numDigits = numDigits - 1 in else begin let numDigits = numDigits + 0 in end
I revised the code and now it works, but I was wondering if there was a way to do it with nested if and less redundancy.
Revised:
let rec rev_int num =
if num / 10 == 0 then
num
else
let temp = num mod 10 in
let numDigits = String.length(string_of_int num) - 1 in
if num < 0 then
let numDigits = numDigits - 1 in
let num = (num - temp) / 10 in
temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num
else
let numDigits = numDigits + 0 in
let num = (num - temp) / 10 in
temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num
==
is very often wrong in OCaml as it checks for physical equality vs. structural equality. You likely wantif num / 10 = 0 then ...
\$\endgroup\$