OCaml类型gtk+类型错误视图

OCaml type gtk+ type error view

在错误下方,您会看到类型

?开始:GText.iter -> ?stop:GText.iter -> ?slice:bool -> ?visible:bool -> unit -> string

这不是和string一样的类型吗?因为函数 return 是一个字符串,而它被传递给的函数需要一个字符串。我以为final -> 之后的最后一个类型是 return 值的类型。我错了吗?

ocamlfind ocamlc -g -package lablgtk2 -linkpkg calculator.ml -o calculator
File "calculator.ml", line 10, characters 2-44:
Warning 10: this expression should have type unit.
File "calculator.ml", line 20, characters 2-54:
Warning 10: this expression should have type unit.
File "calculator.ml", line 29, characters 61-86:
Error: This expression has type
         ?start:GText.iter ->
         ?stop:GText.iter -> ?slice:bool -> ?visible:bool -> unit -> string
       but an expression was expected of type string

Compilation exited abnormally with code 2 at Sun Aug  2 15:36:27

尝试调用

之后
(* Button *)
  let button = GButton.button ~label:"Add"
                              ~packing:vbox#add () in
  button#connect#clicked ~callback: (fun () -> prerr_endline textinput#buffer#get_text ());

它说它是字符串类型 -> 单位并提示我缺少一个 ;

这些编译器错误有点令人困惑。

编辑:显然像 button#connect#clicked ~callback: (fun () -> prerr_endline (textinput#buffer#get_text ()));是正确的,我需要在函数周围放置 (...) 以使 prerr 知道 textinput...() 是一个以 () 作为 arg 而不是传递给 prerr 的 2 个参数的函数。

这很有趣。感谢您的帮助。

这种类型:

?start:GText.iter -> ?stop:GText.iter -> ?slice:bool -> ?visible:bool -> unit -> string

是一个函数,表示returns一个字符串。它与字符串不同。

如类型所示,如果将 () 作为参数传递,您可以获得一个字符串。还有 4 个可选参数。

当函数包含可选参数时,它必须至少包含一个非可选参数。否则无法区分部分应用和实际应用,即函数调用。如果所有参数都是可选的,那么根据约定,类型为 unit 的必需参数将添加到末尾。所以,你的函数实际上 "waits" 直到你提供 () 语句:"all is done, use default for everything else".

TL;DR;添加 () 到你的函数调用的末尾,显示错误。

 ?start:GText.iter -> ?stop:GText.iter -> ?slice:bool -> ?visible:bool -> unit -> string
                                                                          ^^^^
                                                                    required argument
                                                                       of type unit

更新

新问题是您忘记用括号分隔它:

prerr_endline (textinput#buffer#get_text ())

否则,当您向 prerr_endline 提供 3 个参数时,编译器会查看它。