5

I have the following list:

["A";"AA";"ABC";"BCD";"B";"C"]

I am randomly extracting an element from the list. But the element I extract should be of size 3 only not lesser than 3.

I am trying to do this as follows:

let randomnum = (Random.int(List.length (list)));;
let rec code c =
    if (String.length c) = 3 then c
    else (code ((List.nth (list) (randomnum)))) ;;
print_string (code ( (List.nth (list) (randomnum)))) ;;

This works fine if randomly a string of length 3 is picked out from the list.

But the program does not terminate if a string of length < 3 is picked up. I am trying to do a recursive call so that new code keeps getting picked up till we get one of length = 3.

I am unable to figure out why this is does not terminate. Nothing gets output by the print statement.

3 Answers 3

4

What you probably want to write is

 let rec code list =
   let n = Random.int (List.length list) in
   let s = List.nth list in
   if String.length s < 3 then code list else s

Note that, depending on the size of the list and the number of strings of size greater than 3, you might want to work directly on a list with only strings greater than 3:

let code list =
  let list = List.filter (fun s -> String.length s >= 3) list in
  match list with
  | [] -> raise Not_found
  | _  -> List.nth list (Random.int (List.length list)) 

This second function is better, as it always terminate, especially when there are no strings greater than 3.

3

You only pick a random number once. Say you pick 5. You just keep recursing with 5 over and over and over. You need to get a new random number.

0
1

For your code to terminate, it would be better to first filter the list for suitable elements, then take your random number:

let code list =
   let suitables = List.filter (fun x -> String.length x = 3) list in
   match List.length suitables with
   | 0 -> raise Not_found (* no suitable elements at all! *)
   | len -> List.nth suitables (Random.int len)

Otherwise your code would take very long to terminate on a large list of elements with size <> 3; or worse on a list with no element of size 3, it would not terminate at all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.