Filter list items by length - Ocaml

I have the following list:

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

I accidentally extract an item from a list. But the element i extract should have a size of 3, but not less than 3.

I am trying to do it like this:

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 at random a string of length 3 is selected from the list.

But the program does not end if the string is of length <3. I try to make a recursive call so that the new code continues to receive until we get one of length = 3.

I cannot understand why this does not end. The print statement does not print anything. A.

+5
source share
3 answers

. , 5. 5 . .

+3

, , ,

 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

, 3 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)) 

, , 3.

+4

In order for your code to complete, it would be better to first filter the list for suitable elements, and then accept 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 will take a very long time to complete a large list of elements with size <> 3; or, even worse, in a list without an element of size 3, it will not end at all!

+1
source

All Articles