【问题标题】:OCaml - Printing recursive fatorial function return value not workingOCaml - 打印递归fatorial函数返回值不起作用
【发布时间】:2019-03-04 09:06:50
【问题描述】:

我有这个代码:

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

如何打印返回值?

【问题讨论】:

    标签: function recursion ocaml factorial


    【解决方案1】:

    问题是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 应该接受两个参数,然后返回单位。存在差异:Printf.printf fmt n fact 应返回一个可应用于最后一个参数 n 的函数,但它返回单位。 或者换句话说,

    类型 'a -> 'b 与类型单元不兼容

    错误的前半部分

    这个表达式有类型 ('a -> 'b, out_channel, 单位, 单位, 单位, 'a -> 'b) CamlinternalFormatBasics.fmt 但表达式应为类型 ('a -> 'b, out_channel, 单位, 单位, 单位, 单位) CamlinternalFormatBasics.fmt

    是由于格式字符串的类型非常灵活,因此类型检查器只有在发现无法打印格式字符串并返回带有提供的参数的单位时才会失败。

    【讨论】:

      猜你喜欢
      • 2018-04-02
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多