I written the following code to randomly select items n items from a list and place the selections in a new list
The code is below
let random_extract list n =
let l = ((List.length list)- 1)
and acc = [] in
for i = 1 to n do
(List.nth list (Random.int l) ) :: acc (* Line 447 *)
done;
acc
;;
When I load the file that contains this code I get the following error
File "all_code.ml", line 447, characters 2-40:
Warning 10: this expression should have type unit.
val random_extract : 'a list -> int -> 'b list = <fun>
Two questions ,
Question 1: what does this warning mean.
Secondly when I run this function I dont get the list expected but an empty List.
Question 2: how do I get the value of acc from inside the for loop
What Jeffrey Scofield said, and also:
If you are going to use a
forloop for something like that, thenaccmust be a reference, i.e., a mutable value. In Ocaml and ML in generallet x = ...defines an immutable value. Next, when you wrote(List.nth list (Random.int l)) :: acc, that just meant “look, I can make a list”. Nowhere did you say that the newly constructed list has to be assigned to anything, in particular it was not assigned toacc(which it couldn’t, becauseaccis immutable). Ocaml issued a warning because it saw that the body of yourforloop produces a list, but Ocaml knows that the body of aforloop ought to produce a unit (“void” in C/C++/Java mis-terminology).Using a
forloop like that is ugly. The Right Way is to do it like this:If you are new to Ocaml you really should invest time to understand the above code completely. After that, you should study the following code, and make sure you understand why it is more efficient that the first version (look up “tail recursion”):