OCaml Return Values

The book Developing Applications with OCaml has the following explanation regarding return values:

When the value preceding the semicolon is discarded, the Objective CAML issues a warning if it is not of the unit type.

# 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 if 2 has a return value other than unit , because my intention is not to return 2 , but to return 3 . The way I understand this, any instruction preceding my last statement is not the return value of a function, so why a warning?

I have this warning throughout my code, and it becomes clear to me that I really don’t understand how the returned values ​​really work in OCaml.

Thank you for your help.

+8
ocaml return-value
source share
2 answers

Consider the expression e1 ; e2 e1 ; e2 . By definition, the evaluation of this entire expression leads to the evaluation of e1 and then e2 , and the final value of the entire expression is the value of e2 . The result of e1 discarded. This is not a problem if the type e1 is unit , since it has a single value for one resident () . For all other types that discard the result of e1 , information loss is implied, which probably does not correspond to the programmer, therefore a warning. The programmer must explicitly ignore the value of the result, either with ignore or with

 let (_:type) = e1 in e2 

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

+5
source share

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

+4
source share

All Articles