OCaml中的Fizbuzz获取错误“与类型单位不兼容”

时间:2019-05-27 00:09:13

标签: ocaml

我有以下用OCaml编写的fizbuzz程序(使用一点递归):

let rec fizbuzz_r = 
  let rec fizbuzz_rr i = 
    if i == 0 then 
      ()
    else if i mod 3 == 0 && i mod 5 != 0 then
      Printf.printf "Fizz: %d \n" i  
      fizbuzz_rr (i - 1)
    else if i mod 3 != 0 && i mod 5 == 0 then
      Printf.printf "Buzz: %d \n" i 
      fizbuzz_rr (i - 1) 
    else if i mod 5 == 0 && i mod 3 == 0 then
      Printf.printf "Fizbuzz: %d \n" i 
      fizbuzz_rr (i - 1) 
    else 
      Printf.printf "Current Number: %d \n" i 
      fizbuzz_rr (i - 1) 
    ()
  in  
    fizbuzz_rr 100

let () = fizbuzz_r 

问题是当我编译它时,出现以下错误消息:

Error: This expression has type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit,
          'a -> 'b -> 'c -> 'd)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit, unit)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b -> 'c -> 'd is not compatible with type unit 

但是,在我看来,嵌套函数fizbuzz_rr正确返回了unit类型。我在这里想念什么?

1 个答案:

答案 0 :(得分:2)

此表达式:

  Printf.printf "Fizz: %d \n" i  
  fizbuzz_rr (i - 1)

具有以4个参数调用Printf.printf的形式。您需要用分号分隔要使用的两个表达式。

但是,在then之后,您只能使用一个表达式。因此,您需要在两个表达式之间加上括号。看起来像这样:

  . . .
else if i mod 3 == 0 && i mod 5 != 0 then (
  Printf.printf "Fizz: %d \n" i;
  fizbuzz_rr (i - 1)
) else if i mod 3 != 0 && i mod 5 == 0 then (
  . . .

最后您还有一个(),它什么也没做。您应该这样删除它:

else (
  Printf.printf "Current Number: %d \n" i ;
  fizbuzz_rr (i - 1)
)