Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter elements in a list by length - Ocaml

Tags:

random

ocaml

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.

like image 646
JJunior Avatar asked Nov 29 '10 04:11

JJunior


2 Answers

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.

like image 163
Fabrice Le Fessant Avatar answered Oct 02 '22 18:10

Fabrice Le Fessant


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.

like image 32
Brian Avatar answered Oct 02 '22 16:10

Brian