OCaml 嵌套问题 if

Trouble with OCaml nested if

使用我的原始代码,我一直在 let numDigits = numDigits - 1 in

行上得到 Error: Parse error: [expr level ;] expected after "in" (in [expr])

原文:

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

具有以下变化:

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

我修改了代码,现在它可以工作了,但我想知道是否有一种方法可以使用嵌套 if 和更少的冗余来完成它。

修订:

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

来自Hunan Rostomyan

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

    let numDigits = numDigits - (if num < 0 then 1 else 0) in
    let num = (num - temp) / 10 in
    temp * int_of_float(10.0 ** float_of_int numDigits) + rev_int num