Search code examples
functionrandomfunctional-programmingocaml

What is wrong with this code for creating lists in OCaml?


I am trying to create a program in OCaml [randlist len max], which would generate an int list of length len with integers smaller than max.

I am wondering what is wrong with the following code:

let randlist dolzina maksimum =
  let rec aux dolz maks acc =
    match (List.length acc) with
    | dolz -> acc
    | _ -> aux dolz maks ((Random.int maks) :: acc)
  in
  aux dolzina maksimum []

This always returns an empty list and I do not understand why.

Another thing that confuses me is what goes wrong with the following code:

let randlist dolzina maksimum =
  Random.self_init ()
  let rec aux dolz maks acc =
    match (List.length acc) with
    | dolz -> acc
    | _ -> aux dolz maks ((Random.int maks) :: acc)
  in
  aux dolzina maksimum []

As soon as I add the Random.self init () the whole code crashes. What exactly does Random.self_init do, when and how do I use it?


Solution

  • Pattern matching deconstructs values that match a pattern into smaller parts, it doesn't test equality. In other words, your first case

    match List.length acc with
    | dolz -> acc
    

    reads: take the value returned by List.length acc, name it dolz in the right hand side of the arrow ->, and run the code after ->. Notice that this means that dolz matches any values. This is why the compiler warns you that the second case

    | _ -> aux dolz maks ((Random.int maks) :: acc)
    

    is never used.

    For your second question, the code cannot crash, since your code is not well-typed and thus cannot compile. Random.self_init initialize the seed of the PRNG. You should call it once in your program, and not at every calls of randlist.