vendredi 27 septembre 2019

How to find an element in a list at a random position?

I'm new to OCaml and I have this little exercise I need to do. It consists in writing a function that retrieves an element of a list at a random position. I already have a piece of code, but it has major errors, I don't know to put some parts together to make it work: the Random.int, the find-nth function.

What I would like to do is using a Random.int in my find-nth function, and being able to use the find-nth function.

Here's what I've done so far :

let choose l = 
  let rand = Random.int(List.length l) in
  let rec nth l rand = 
    match l with
    | [] -> failwith "Liste vide"
    | e1::l' -> if rand == 0 then e1 else nth l' (rand-1) in;;

For the expected results, it would return an element taken from a random position in the list. I basically have a syntax error with this code.

Thanks




Aucun commentaire:

Enregistrer un commentaire