简体   繁体   中英

expression expected type unit, but it already does

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

Compiling this tells me that ("hello"; ()) 'should have type unit'

In fact, I get the same warning with this code

let _ = "hello"; ()

or this code

let _ = ("hello"; ())

But it does have type unit ... doesn't it?

The expression :

 let f  = "hello";1;;

Triggers the warning :

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

This is because you are trying to return a first value via "hello", and then you return 1 meaning that ocaml must disregard "hello". if you replace it by unit - meaning "here I return nothing", it will be ok.

The expression :

let f = (); 1;;

raises no warning and f is an int .

So the warning you are getting is related to the inner code of your expression, not to the type of the expression you have written.

let f = "hello";();;

The compiler warns you that you compute something that you disregard after that ("hello" is never used, and the return value is of f is () ). But, as you have noted, f has type unit .

In utop :

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

You get :

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

which locates exactly to the position of "hello" string - but does not locate to ("hello"; ()) . ("hello"; ()) has type unit, exactly like print_endline "hi" .

The warning is just about the fact that the expression that should be instead of "hello"; is expected to have type unit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM