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 for
does 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 returning true
or false
.
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 the ref
function 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:
let f q p rho=
let x = ref [] in
if q > p then
for i=0 to rho do
x := q :: !x
done;
!x;;
This kind of loop is probably best expressed using recursion:
let f q p rho=
let rec loop i =
if i > rho then
[]
else
q::(loop (i+1))
in
if q > p then
loop 0
else
[];;
Or we can make it tail recursive:
let f q p rho=
let rec loop i acc =
if i > rho then
acc
else
loop (i+1) (q::acc)
in
if q > p then
loop 0 []
else
[];;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With