【问题标题】:Error: This expression has type (int * int) option but an expression was expected of type 'a * 'b错误:此表达式具有类型 (int * int) 选项,但表达式应为 'a * 'b 类型
【发布时间】:2015-12-31 09:21:10
【问题描述】:

如果我将这段代码逐行放到 utop 中,那么它可以工作,但是如果我将它编译为程序,那么我会看到错误。

module List = Core.Std.List;;

let () =
    let shifts  = [ (-1, -1); (0, -1) ] in
    let first = List.nth shifts 0 in
    let (a, b) = first in
    Printf.printf "%d %d\n" a b;
;;

还有错误信息:

Error: This expression has type (int * int) option
       but an expression was expected of type 'a * 'b

类型有什么问题以及为什么它在 utop 中有效?

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    在我看来,Core.Std.List.nth 具有 'a list -> int -> 'a option 类型,以便处理 int 超出范围的情况。标准库List.nth 的类型为'a list -> int -> 'a。它会引发超出范围的 int 异常。

    如果您在一种情况下使用Core.Std.List,但在另一种情况下使用标准List,这将解释差异。

    【讨论】:

    • 谢谢!我完全忘记了 List 的两个版本。似乎总是使用open Core.Std 它比只打开一个名称要好。我只导入 List 的原因 - 在我的代码中我使用 Array.make 并且 Core.Std.Array 中不存在此方法。
    • @grigoriytretyakov 在 Core 中有 Array.create 的功能完全相同。是的,最好总是open Core.Std。在这种情况下,您可以使用Caml 模块访问标准库,如Caml.Array.make
    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多