Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml 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 function, 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.

like image 719
Sergi Mansilla Avatar asked Jun 15 '11 06:06

Sergi Mansilla


2 Answers

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).

like image 187
ygrek Avatar answered Oct 08 '22 07:10

ygrek


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 ....

like image 43
akoprowski Avatar answered Oct 08 '22 08:10

akoprowski