Warning 10: this expression must be of type unit

I am writing a program in ocaml containing several “for” loops, my problem is that for each of these loops you get this message: “warning 10: this expression must be of type one”.

Example:

let fqp rho= let x = [] in if q > p then for i=0 to rho do x= q :: x done; x;; 

This is every time I use the "for" loop, how can I solve this problem?

+6
ocaml
source share
2 answers

There are several problems in your code.

The error is that for does not return anything, so the inside of the loop should be pure for a side effect. Therefore, it must be of type unit. Your use of = not of the unit type, because = is actually an equality operator comparing two values ​​and returning true or false .

So you are using the wrong operator. It looks like you are trying to "assign" x . But in ML you cannot assign "variables" because they are bound to a value when they are defined and cannot change. One way to get variability is to use a mutable cell (called a "link"): you use the ref function to create a mutable cell from an initial value; operator ! to get its value; and operator := to change the value inside.

So for example:

 let fqp rho= let x = ref [] in if q > p then for i=0 to rho do x := q :: !x done; !x;; 
+8
source share

This kind of loop is probably best expressed with recursion:

 let fqp 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 fqp 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 [];; 
+3
source share

All Articles