I’m writing a program in ocaml containing some loops “for”, my problem is that for each of these cycles you receive this message: “warning 10 : this expression should have type unit. “
Example :
let f q p rho=
let x = [] in
if q > p then
for i=0 to rho do
x= q :: x
done;
x;;
this every time I use a cycle “for” ,how can I solve this problem?
There are several problems with your code.
The error is because the
fordoes not return anything, and so the inside of the loop to be purely for side-effect. So it should have unit type. Your use of=does not have unit type, because=is in fact the equality operator, comparing two values, and returningtrueorfalse.So you are using the wrong operator. It appears that you are trying to “assign” to
x. But in ML, you cannot assign to “variables”, because they are bound to a value when they are defined and cannot change. One way to get mutability, is to use a mutable cell (called a “reference”): you use thereffunction to create the mutable cell from an initial value; the!operator to get its value out; and the:=operator to change the value inside.So for example: