表达式预期类型单元,但已经做到了


let _ =
    try ("hello"; ()) with
    | _ -> print_endline "hi"

编译此事告诉我,("hello"; ())'应该具有类型单元'

实际上,我对此代码得到了相同的警告

let _ = "hello"; ()

或此代码

let _ = ("hello"; ())

但是它 die 有类型unit ...不是吗?

表达式:

 let f  = "hello";1;;

触发警告:

 this expression should have type unit - around "hello" string.

这是因为您试图通过" Hello"返回第一个值,然后返回1,这意味着Ocaml必须无视" Hello"。 如果您用unit替换它 - 意思是"我什么都没返回",那就可以了。

表达式:

let f = (); 1;;

没有提示,fint

因此,您获得的警告与表达式的内部代码有关,而不是与您写的表达式的类型有关。

let f = "hello";();;

编译器警告您,您在此之后忽略了某些内容(" Hello"从未使用过,并且返回值是f())。但是,如您所指出的那样,f具有unit类型。

utop中:

let _ = try ("hello"; ()) with
    | _ -> print_endline "hi";;

您得到:

Characters 13-20:
Warning 10: this expression should have type unit.

精确地定位到"hello"字符串的位置 - 但未定位到("hello"; ())("hello"; ())具有类型单元,就像print_endline "hi"一样。

警告仅是关于应该代替"hello";具有类型单元的表达式的事实。

最新更新