OCaml - 打印递归阶乘函数 return 值不起作用

OCaml - Printing recursive fatorial function return value not working

我有这个代码:

let n = read_int()
let rec fact n = if n=0 then 1 else n*fact(n-1)
let () = Printf.printf "%d factorial is %d.\n" n fact(n)

我编译然后编译器说:

File "fat.ml", line 3, characters 23-46:
Error: This expression has type
         ('a -> 'b, out_channel, unit, unit, unit, 'a -> 'b)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b, out_channel, unit, unit, unit, unit)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b is not compatible with type unit

如何打印返回值?

问题是 fact n:

周围缺少括号
let () = Printf.printf "%d factorial is %d.\n" n (fact n)

有效。

您遇到复杂类型错误的原因是编译器读取

let () = Printf.printf "%d factorial is %d.\n" n fact(n)

作为

let () = Printf.printf "%d factorial is %d.\n" n fact n

换句话说,对于编译器函数 printf 适用于 4 个参数:"%d factorial is %d.\n"nfactn.

但是格式字符串,我们称之为 fmt,只包含两个 %d 说明符。因此编译器也知道 printf fmt 应该有两个参数,然后是 returns 单元。存在差异:Printf.printf fmt n fact 预期 returns 可以应用于最后一个参数的函数 n 但它是 returns 单元。 或者换句话说,

Type 'a -> 'b is not compatible with type unit

错误的前半部分

This expression has type ('a -> 'b, out_channel, unit, unit, unit, 'a -> 'b) CamlinternalFormatBasics.fmt but an expression was expected of type ('a -> 'b, out_channel, unit, unit, unit, unit) CamlinternalFormatBasics.fmt

是由于格式字符串的类型非常灵活,因此类型检查器只有在发现无法打印格式字符串和returns单元时才会失败。参数。