开发者

OCaml return values

开发者 https://www.devze.com 2023-03-12 21:11 出处:网络
In the book \'Developing Applications with OCaml\', there is the following explanation regarding return values:

In the book 'Developing Applications with OCaml', there is the following explanation regarding return values:

As the value preceding a semicolon is discarded, Objective CAML gives a warning when it is not of type unit.

# print_int 1; 2 ; 3 ;;
Characters 14-15:
Warning: this expression should have type unit.
1- : int = 3


To avoid this message, you can use the
function ignore:

# print_int 1; ignore 2; 3 ;; 
1- : int = 3`

I don't understand why it would be a problem that 2 has a return value diferent than unit, because my intention is not to return 2, but to return 3. The way I understand it, any instruction preceding my very last instruction is not the return value of the fun开发者_开发技巧ction, so why the warning?

I've been having this warning all over my code and it is becoming clear to me that I don't really understand how return values really work in OCaml.

Thanks for your help.


Consider expression e1 ; e2. By definition - evaluating this whole expression results in evaluation of e1 and then e2 and the resulting value of the whole expression is the value of e2. Value result of e1 is discarded. This is not the problem if the type of e1 is unit cause it has the only single inhabitant value (). For all the other types discarding the result of e1 means loosing information which is probably not what the programmer intended, hence the warning. The programmer has to explicitely ignore the result value, either with ignore or with

let (_:type) = e1 in
e2

Type annotation can be omitted but it may be useful to be sure that e1 is fully evaluated to the expected type (not a partial application).


Well, the warning is there because the fact that you produce a value but then don't use it may be (and very often is) an indication that you are doing something wrong. If you don't agree with this policy you can turn off that warning. But as usual it's a good practice not to do that, in which case, if you really don't need a value of an expression you can indeed use ignore or bind it to _, as in let _ = f() in ....

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号